Java Code Examples for android.graphics.BitmapFactory

The following are top voted examples for showing how to use android.graphics.BitmapFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Phoenix-for-VK   File: NotificationHelper.java   Source Code and License 7 votes vote down vote up
public void buildNotification(Context context, final String albumName, final String artistName,
                              final String trackName, final Long albumId, final Bitmap albumArt,
                              final boolean isPlaying, MediaSessionCompat.Token mediaSessionToken) {

    if (Utils.hasOreo()){
        mNotificationManager.createNotificationChannel(AppNotificationChannels.getAudioChannel(context));
    }
    // Notification Builder
    mNotificationBuilder = new NotificationCompat.Builder(mService, AppNotificationChannels.AUDIO_CHANNEL_ID)
            .setShowWhen(false)
            .setSmallIcon(R.drawable.itunes)
            .setContentTitle(artistName)
            .setContentText(trackName)
            .setContentIntent(getOpenIntent(context))
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.cover))
            .setPriority(Notification.PRIORITY_MAX)
            .setStyle(new MediaStyle()
                    .setMediaSession(mediaSessionToken)
                    .setShowCancelButton(true)
                    .setShowActionsInCompactView(0, 1, 2)
                    .setCancelButtonIntent(retreivePlaybackActions(4)))
            .addAction(new android.support.v4.app.NotificationCompat.Action(R.drawable.page_first, ""
                    , retreivePlaybackActions(3)))
            .addAction(new android.support.v4.app.NotificationCompat.Action(isPlaying ? R.drawable.pause : R.drawable.play, ""
                    , retreivePlaybackActions(1)))
            .addAction(new android.support.v4.app.NotificationCompat.Action(R.drawable.page_last, ""
                    , retreivePlaybackActions(2)));

    mService.startForeground(APOLLO_MUSIC_SERVICE, mNotificationBuilder.build());
}
 
Example 2
Project: PaoMovie   File: SendPaoPaoPic.java   Source Code and License 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	// TODO Auto-generated method stub
	super.onActivityResult(requestCode, resultCode, data);
	paoPaoQuan.setSelection(paoPaoState);
	// requestCode标示请求的标示 resultCode表示有数据
	Log.d("js", requestCode + "//" + resultCode + "**" + data);
	if (requestCode==4||data != null) {
		int childCount = imageGrid.getChildCount();
		if (childCount > 9) {
			Toast.makeText(this, "最多选择9张图片", 1).show();
		} else {
			imageId++;
			String fPath = null;
			if (requestCode == 4) {
				fPath = mCurrentPhotoPath;
			}else{
				Uri uri = data.getData(); // 得到Uri
				if((uri!=null&&!uri.equals(""))){
					fPath = StaticMethod.getImageAbsolutePath(this, uri); // 转化为路径
				}
			}
			Bitmap b = BitmapFactory.decodeFile(fPath);
			b = StaticMethod.getThumImg(b, 100);
			ImageView image = new ImageView(this);
			image.setLayoutParams(new LayoutParams(130, 130));
			image.setScaleType(ScaleType.FIT_XY);
			image.setId(imageId);
			image.setTag(fPath);
			image.setImageBitmap(b);
			image.setOnClickListener(this);
			imageGrid.addView(image, childCount - 1);
			}
	}

}
 
Example 3
Project: cordova-plugin-image-picker   File: MultiImageChooserActivity.java   Source Code and License 6 votes vote down vote up
private Bitmap tryToGetBitmap(File file, BitmapFactory.Options options, int rotate, boolean shouldScale) throws IOException, OutOfMemoryError {
    Bitmap bmp;
    if (options == null) {
        bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
    } else {
        bmp = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
    }
    if (bmp == null) {
        throw new IOException("The image file could not be opened.");
    }
    if (options != null && shouldScale) {
        float scale = calculateScale(options.outWidth, options.outHeight);
        bmp = this.getResizedBitmap(bmp, scale);
    }
    if (rotate != 0) {
        Matrix matrix = new Matrix();
        matrix.setRotate(rotate);
        bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
    }
    return bmp;
}
 
Example 4
Project: GitHub   File: MyApplication.java   Source Code and License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    appInstance = this;
    AndroidNetworking.initialize(getApplicationContext());
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPurgeable = true;
    AndroidNetworking.setBitmapDecodeOptions(options);
    AndroidNetworking.enableLogging();
    AndroidNetworking.setConnectionQualityChangeListener(new ConnectionQualityChangeListener() {
        @Override
        public void onChange(ConnectionQuality currentConnectionQuality, int currentBandwidth) {
            Log.d(TAG, "onChange: currentConnectionQuality : " + currentConnectionQuality + " currentBandwidth : " + currentBandwidth);
        }
    });

}
 
Example 5
Project: ForeverLibrary   File: PictureUtil.java   Source Code and License 6 votes vote down vote up
/**
     * 质量压缩
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > MAXSIZEKB) {  //循环判断如果压缩后图片是否大于300kb,大于继续压缩
//			Log.i("-----", "compressImage: options="+options+"--baos.toByteArray().length="+baos.toByteArray().length);
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        Log.e("压缩之后的图片大小", "compressImage: 111111options=  " + options + "--baos.toByteArray().length=  " + baos.toByteArray().length);
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }
 
Example 6
Project: DisplayingBitmaps   File: ImageResizer.java   Source Code and License 6 votes vote down vote up
/**
 * Decode and sample down a bitmap from resources to the requested width and height.
 *
 * @param res The resources object containing the image data
 * @param resId The resource id of the image data
 * @param reqWidth The requested width of the resulting bitmap
 * @param reqHeight The requested height of the resulting bitmap
 * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap
 * @return A bitmap sampled down from the original with the same aspect ratio and dimensions
 *         that are equal to or greater than the requested width and height
 */
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight, ImageCache cache) {

    // BEGIN_INCLUDE (read_bitmap_dimensions)
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    // END_INCLUDE (read_bitmap_dimensions)

    // If we're running on Honeycomb or newer, try to use inBitmap
    if (Utils.hasHoneycomb()) {
        addInBitmapOptions(options, cache);
    }

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}
 
Example 7
Project: Huochexing12306   File: ShareUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 根据磁盘路径取得
 * @param pathString
 * @return
 */
public Bitmap getDiskBitmap(String pathString)  
{  
    Bitmap bitmap = null;  
    try  
    {  
        File file = new File(pathString);  
        if(file.exists())  
        {  
            bitmap = BitmapFactory.decodeFile(pathString);  
        }
    } catch (Exception e)  
    {  
    	e.printStackTrace();
    	return null;
    }  
    return bitmap;  
}
 
Example 8
Project: Watermark   File: CropPresenter.java   Source Code and License 6 votes vote down vote up
private int calculateSampleSize(BitmapFactory.Options options) {
    int outHeight = options.outHeight;
    int outWidth = options.outWidth;
    int sampleSize = 1;
    int destHeight = 1000;
    int destWidth = 1000;
    if (outHeight > destHeight || outWidth > destHeight) {
        if (outHeight > outWidth) {
            sampleSize = outHeight / destHeight;
        } else {
            sampleSize = outWidth / destWidth;
        }
    }
    if (sampleSize < 1) {
        sampleSize = 1;
    }
    return sampleSize;
}
 
Example 9
Project: editor-sql   File: FeThumbUtils.java   Source Code and License 6 votes vote down vote up
private static int computeInitialSampleSize(BitmapFactory.Options options,
                                            int minSideLength, int maxNumOfPixels) {
    double w = options.outWidth;
    double h = options.outHeight;
    int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 : (int) Math
            .ceil(Math.sqrt(w * h / maxNumOfPixels));
    int upperBound = (minSideLength == UNCONSTRAINED) ? 128 : (int) Math
            .min(Math.floor(w / minSideLength),
                    Math.floor(h / minSideLength));
    if (upperBound < lowerBound) {
        // return the larger one when there is no overlapping zone.
        return lowerBound;
    }
    if ((maxNumOfPixels == UNCONSTRAINED)
            && (minSideLength == UNCONSTRAINED)) {
        return 1;
    } else if (minSideLength == UNCONSTRAINED) {
        return lowerBound;
    } else {
        return upperBound;
    }
}
 
Example 10
Project: Mobike   File: QrUtils.java   Source Code and License 6 votes vote down vote up
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is getUrl power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}
 
Example 11
Project: BluetoothAPP   File: DialogUtil.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dialog_define);
    setCanceledOnTouchOutside(true);
    ImageView img =findViewById(R.id.dialog_img);
    pro =findViewById(R.id.dialog_progress);
    ContentResolver cr = context.getContentResolver();
    try {
        Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(path));
        img.setImageBitmap(bitmap);
    } catch (FileNotFoundException e) {
        Log.e("Exception", e.getMessage(),e);
    }

    pro.setMax(progreesmax);
    new SendSocketService() .setProgressListener(new SendSocketService.setProgessIml() {
        @Override
        public void setProgress(int size) {
            pro.setMax(size);
        }
    });

    pro.setProgress(getProgrees);

}
 
Example 12
Project: Resizer   File: ImageUtils.java   Source Code and License 6 votes vote down vote up
public static Bitmap getScaledBitmap(int targetLength, File sourceImage) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = false;
    Bitmap bitmap = BitmapFactory.decodeFile(sourceImage.getAbsolutePath(), options);

    // Get the dimensions of the original bitmap
    int originalWidth = options.outWidth;
    int originalHeight = options.outHeight;
    float aspectRatio = (float) originalWidth / originalHeight;

    // Calculate the target dimensions
    int targetWidth, targetHeight;

    if (originalWidth > originalHeight) {
        targetWidth = targetLength;
        targetHeight = Math.round(targetWidth / aspectRatio);
    } else {
        aspectRatio = 1 / aspectRatio;
        targetHeight = targetLength;
        targetWidth = Math.round(targetHeight / aspectRatio);
    }

    return Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true);
}
 
Example 13
Project: GongXianSheng   File: ImageUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 根据宽高路径返回图片
 */
public static Bitmap decodeScaleImage(String paramString, int width, int height)
{
	BitmapFactory.Options localOptions = getBitmapOptions(paramString);
	int i = calculateInSampleSize(localOptions, width, height);
	localOptions.inSampleSize = i;
	localOptions.inJustDecodeBounds = false;
	Bitmap localBitmap1= null;
	try{
		localBitmap1 = BitmapFactory.decodeFile(paramString, localOptions);
	}
	catch (Exception e){
		e.printStackTrace();
	}
	int j = readPictureDegree(paramString); //获取旋转角度
	Bitmap localBitmap2 = null;
	if ((localBitmap1 != null) && (j != 0))
	{
		localBitmap2 = rotaingImageView(j, localBitmap1);
		localBitmap1.recycle();
		localBitmap1 = null;
		return localBitmap2;
	}
	return localBitmap1;
}
 
Example 14
Project: BatteryModPercentage   File: NotifService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onPreExecute() {
    b = new NotificationCompat.Builder(context);
    nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Intent resultIntent = new Intent(context, MainActivity.class);

    resultPendingIntent =
            PendingIntent.getActivity(
                    context,
                    0,
                    resultIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );

    b.setAutoCancel(false)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon))
            .setSmallIcon(R.drawable.ic_battery_mgr_mod)
            .setPriority(NotificationCompat.PRIORITY_MIN)
            .setContentIntent(resultPendingIntent)
            .setOngoing(true)
    ;

}
 
Example 15
Project: LiveWallpaper   File: MainActivity.java   Source Code and License 6 votes vote down vote up
/**
     * 使用Bitmap设置壁纸
     * 直接设置为壁纸,不会有任何界面和弹窗出现
     * 壁纸切换,会有动态的渐变切换
     *
     * @param view
     */
    public void onSetWallpaperForBitmap(View view) {
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
        try {
            Bitmap wallpaperBitmap = BitmapFactory.decodeResource(getResources(), R.raw.girl);
            wallpaperManager.setBitmap(wallpaperBitmap);
//            setWallpaper(wallpaperBitmap);
//            setWallpaper(getResources().openRawResource(R.raw.girl));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example 16
Project: android-slideshow   File: FileItemHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the mime type of the given item.
 */
public String getImageMimeType(FileItem item){
	String mime = "";
	try {
		mime = URLConnection.guessContentTypeFromName(item.getPath());
	} catch (StringIndexOutOfBoundsException e){
		// Not sure the cause of this issue but it occurred on production so handling as blank mime.
	}

	if (mime == null || mime.isEmpty()){
		// Test mime type by loading the image
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(item.getPath(), opt);
		mime = opt.outMimeType;
	}

	return mime;
}
 
Example 17
Project: com.ruuvi.station   File: ScannerService.java   Source Code and License 6 votes vote down vote up
public void startFG() {
    Intent notificationIntent = new Intent(this, MainActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    NotificationCompat.Builder notification;
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    notification
            = new NotificationCompat.Builder(getApplicationContext())
            .setContentTitle(this.getString(R.string.scanner_notification_title))
            .setSmallIcon(R.mipmap.ic_launcher_small)
            .setTicker(this.getString(R.string.scanner_notification_ticker))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(this.getString(R.string.scanner_notification_message)))
            .setContentText(this.getString(R.string.scanner_notification_message))
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setLargeIcon(bitmap)
            .setContentIntent(pendingIntent);

    startForeground(notificationId, notification.build());
}
 
Example 18
Project: letv   File: ImageActivity.java   Source Code and License 6 votes vote down vote up
private Bitmap a(String str) throws IOException {
    int i = 1;
    Options options = new Options();
    options.inJustDecodeBounds = true;
    Uri parse = Uri.parse(str);
    InputStream openInputStream = getContentResolver().openInputStream(parse);
    if (openInputStream == null) {
        return null;
    }
    BitmapFactory.decodeStream(openInputStream, null, options);
    openInputStream.close();
    int i2 = options.outWidth;
    int i3 = options.outHeight;
    while (i2 * i3 > 4194304) {
        i2 /= 2;
        i3 /= 2;
        i *= 2;
    }
    options.inJustDecodeBounds = false;
    options.inSampleSize = i;
    return BitmapFactory.decodeStream(getContentResolver().openInputStream(parse), null, options);
}
 
Example 19
Project: android-lite-utils   File: BitmapUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 计算采样率
 *
 * @param options
 * @param reqWidth
 * @param reqHeight
 * @return
 */
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        final int halfHeight = height / 2;
        final int halfWidth = width / 2;
        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}
 
Example 20
Project: fancydownloader   File: MainActivity.java   Source Code and License 6 votes vote down vote up
public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}
 
Example 21
Project: GxIconAndroid   File: IconDialog.java   Source Code and License 6 votes vote down vote up
private void returnPickIcon() {
    Bitmap bitmap = null;
    try {
        bitmap = BitmapFactory.decodeResource(getResources(), iconBean.getId());
    } catch (Exception e) {
        e.printStackTrace();
    }

    Intent intent = new Intent();
    if (bitmap != null) {
        intent.putExtra("icon", bitmap);
        intent.putExtra("android.intent.extra.shortcut.ICON_RESOURCE", iconBean.getId());
        intent.setData(Uri.parse("android.resource://" + getContext().getPackageName()
                + "/" + String.valueOf(iconBean.getId())));
        getActivity().setResult(Activity.RESULT_OK, intent);
    } else {
        getActivity().setResult(Activity.RESULT_CANCELED, intent);
    }
    getActivity().finish();
}
 
Example 22
Project: GitHub   File: ImageLoader.java   Source Code and License 6 votes vote down vote up
/**
     * From Assets
     *
     * @param imageUri
     * @param imageView
     * @throws java.io.IOException
     */
    protected void displayImageFromAssets(String imageUri, ImageView imageView) throws IOException {
        String filePath = Scheme.ASSETS.crop(imageUri);
        Bitmap bitmap;
        try {
            bitmap = BitmapFactory.decodeStream(context.getAssets().open(filePath));
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        if (imageView != null) {
//            imageView.setImageBitmap(bitmap);
            Glide.with(context).load(inputStreamToByte(context.getAssets().open(filePath))).into(imageView);
//            Log.i("杭鹏伟", " " + imageUri + " " + filePath);
        }
    }
 
Example 23
Project: AndroidBookTest   File: DownloadService.java   Source Code and License 6 votes vote down vote up
private Notification getNotification(String title,int progress){
    Intent intent=new Intent(this,MainActivity.class);
    PendingIntent pi=PendingIntent.getActivity(this,0,intent,0);
    NotificationCompat.Builder builder=new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.mipmap.ic_launcher);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
    builder.setContentIntent(pi);
    builder.setContentTitle(title);
    if (progress>=0){
        //当progress大于等于0时才显示下载进度
        builder.setContentText(progress+"%");
        builder.setProgress(100,progress,false);
    }
    return  builder.build();

}
 
Example 24
Project: SmartMath   File: FlatChart.java   Source Code and License 6 votes vote down vote up
public void initialize()	{
	// mcontext should be always not null.
	mcfgImage_24 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.setting_gear_24);
	mcfgImage_32 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.setting_gear_32);
	mcfgImage_48 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.setting_gear_48);
	mcfgImage_64 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.setting_gear_64);
	mzoomInImage_24 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_in_24);
	mzoomInImage_32 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_in_32);
	mzoomInImage_48 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_in_48);
	mzoomInImage_64 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_in_64);
	mzoomOutImage_24 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_out_24);
	mzoomOutImage_32 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_out_32);
	mzoomOutImage_48 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_out_48);
	mzoomOutImage_64 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_out_64);
	mxy1To1ZoomImage_24 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_1_24);
	mxy1To1ZoomImage_32 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_1_32);
	mxy1To1ZoomImage_48 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_1_48);
	mxy1To1ZoomImage_64 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_1_64);
	mfitZoomImage_24 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_fit_24);
	mfitZoomImage_32 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_fit_32);
	mfitZoomImage_48 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_fit_48);
	mfitZoomImage_64 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.zoom_fit_64);
}
 
Example 25
Project: pc-android-controller-android   File: ImageCompressUtil.java   Source Code and License 6 votes vote down vote up
private static int calculateInSampleSize(BitmapFactory.Options options,
                                  int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        } else {
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }
    }
    return inSampleSize;
}
 
Example 26
Project: GitHub   File: WebpBitmapFactoryImpl.java   Source Code and License 5 votes vote down vote up
@DoNotStrip
private static byte[] getInTempStorageFromOptions(@Nullable final BitmapFactory.Options options) {
  if (options != null && options.inTempStorage != null) {
    return options.inTempStorage;
  } else {
    return new byte[IN_TEMP_BUFFER_SIZE];
  }
}
 
Example 27
Project: PhotoApp   File: ImageUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Decodifica a imagem para o tamanho especificado
 */
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {

    // Primeiro decodifica para verificar as dimensões
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calcula inSampleSize - O valor correspondende para a imagem ser redimensionada
    options.inSampleSize = ImageUtil.calculateInSampleSize(options, reqWidth, reqHeight);

    // Decodifica imagem usando o valor calculado
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}
 
Example 28
Project: BBSSDK-for-Android   File: ImageUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 获取bitmap
 *
 * @param fd        文件描述
 * @param maxWidth  最大宽度
 * @param maxHeight 最大高度
 * @return bitmap
 */
public static Bitmap getBitmap(final FileDescriptor fd, final int maxWidth, final int maxHeight) {
	if (fd == null) {
		return null;
	}
	BitmapFactory.Options options = new BitmapFactory.Options();
	options.inJustDecodeBounds = true;
	BitmapFactory.decodeFileDescriptor(fd, null, options);
	options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
	options.inJustDecodeBounds = false;
	return BitmapFactory.decodeFileDescriptor(fd, null, options);
}
 
Example 29
Project: rental-calc   File: PictureViewActivity.java   Source Code and License 5 votes vote down vote up
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    getMenuInflater().inflate(R.menu.picture_view_menu, menu);

    // Locate MenuItem with ShareActionProvider
    MenuItem item = menu.findItem(R.id.action_share);

    // Fetch ShareActionProvider
    ShareActionProvider shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
    if (shareActionProvider == null)
    {
        Log.w(TAG, "Failed to find share action provider");
        return false;
    }

    if(imageFilename == null)
    {
        Log.w(TAG, "No receipt to share");
        return false;
    }

    Intent shareIntent = new Intent(Intent.ACTION_SEND);

    // Determine mimetype of image
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imageFilename, opt);
    shareIntent.setType(opt.outMimeType);

    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(imageFilename)));
    shareActionProvider.setShareIntent(shareIntent);

    return super.onCreateOptionsMenu(menu);
}
 
Example 30
Project: Cable-Android   File: ScribbleActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (resultCode == RESULT_OK) {
    if (requestCode == SELECT_STICKER_REQUEST_CODE) {
      if (data != null) {
        toolbar.setStickerSelected(true);
        final String stickerFile = data.getStringExtra(StickerSelectActivity.EXTRA_STICKER_FILE);

        new AsyncTask<Void, Void, Bitmap>() {
          @Override
          protected @Nullable
          Bitmap doInBackground(Void... params) {
            try {
              return BitmapFactory.decodeStream(getAssets().open(stickerFile));
            } catch (IOException e) {
              Log.w(TAG, e);
              return null;
            }
          }

          @Override
          protected void onPostExecute(@Nullable Bitmap bitmap) {
            addSticker(bitmap);
          }
        }.execute();
      }
    }
  }
}
 
Example 31
Project: Clipcon-AndroidClient   File: RetrofitDownloadData.java   Source Code and License 5 votes vote down vote up
/**
 * Download Captured Image Data
 * Change to Image object from file form of Image data
 */
private void downloadCapturedImageData(InputStream inputStream) {
   // inputStream -> bitmap -> file
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    Bitmap imageBitmapData = BitmapFactory.decodeStream(bufferedInputStream);

    imageToGallery(imageBitmapData);
}
 
Example 32
Project: buildAPKsSamples   File: Bouncer.java   Source Code and License 5 votes vote down vote up
private void setupShape() {
    mBitmap = BitmapFactory.decodeResource(getResources(),
            R.drawable.electricsheep);
    mShapeW = mBitmap.getWidth();
    mShapeH = mBitmap.getHeight();
    setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startAnimation();
        }
    });
}
 
Example 33
Project: QrCode   File: CaptureHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void handleMessage(Message message) {
    switch (message.what) {
        case AUTO_FOCUS:
            if (state == State.PREVIEW) {
                cameraManager.requestAutoFocus(this, AUTO_FOCUS);
            }
            break;
        case RESTART_PREVIEW:
            restartPreviewAndDecode();
            break;
        case DECODE_SUCCEEDED:
            state = State.SUCCESS;
            Bundle bundle = message.getData();
            Bitmap barcode = null;
            float scaleFactor = 1.0f;
            if (bundle != null) {
                byte[] compressedBitmap = bundle.getByteArray(DecodeThread.BARCODE_BITMAP);
                if (compressedBitmap != null) {
                    barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null);
                    // Mutable copy:
                    barcode = barcode.copy(Bitmap.Config.ARGB_8888, true);
                }
                scaleFactor = bundle.getFloat(DecodeThread.BARCODE_SCALED_FACTOR);
            }
            mIScanCallback.handleDecode((Result) message.obj, barcode, scaleFactor);
            break;
        case DECODE_FAILED:
            // We're decoding as fast as possible, so when one decode fails, start another.
            state = State.PREVIEW;
            cameraManager.requestPreviewFrame(decodeThread.getHandler(), DECODE);
            break;
        case RETURN_SCAN_RESULT:
            break;
    }
}
 
Example 34
Project: RLibrary   File: ImageUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 获取bitmap
 *
 * @param data      数据
 * @param offset    偏移量
 * @param maxWidth  最大宽度
 * @param maxHeight 最大高度
 * @return bitmap
 */
public static Bitmap getBitmap(byte[] data, int offset, int maxWidth, int maxHeight) {
    if (data.length == 0) return null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(data, offset, data.length, options);
    options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeByteArray(data, offset, data.length, options);
}
 
Example 35
Project: chromium-for-android-56-debug-video   File: LogoView.java   Source Code and License 5 votes vote down vote up
/**
 * @return The default logo.
 */
private Bitmap getDefaultLogo() {
    Bitmap defaultLogo = sDefaultLogo == null ? null : sDefaultLogo.get();
    if (defaultLogo == null) {
        defaultLogo = BitmapFactory.decodeResource(getResources(), R.drawable.google_logo);
        sDefaultLogo = new WeakReference<Bitmap>(defaultLogo);
    }
    return defaultLogo;
}
 
Example 36
Project: com.ruuvi.station   File: AlarmChecker.java   Source Code and License 5 votes vote down vote up
private static void sendAlert(int stringResId, int _id, String name, Context context) {
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);

    int notificationid = _id + stringResId;

    boolean isShowing = isNotificationVisible(context, notificationid);

    NotificationCompat.Builder notification;

    if (!isShowing) {
        notification
                = new NotificationCompat.Builder(context)
                .setContentTitle(name)
                .setSmallIcon(R.mipmap.ic_launcher_small)
                .setTicker(name + " " + context.getString(stringResId))
                .setStyle(new NotificationCompat.BigTextStyle().bigText(context.getString(stringResId)))
                .setContentText(context.getString(stringResId))
                .setDefaults(Notification.DEFAULT_ALL)
                .setOnlyAlertOnce(true)
                .setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setLargeIcon(bitmap);

        NotificationManager NotifyMgr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        NotifyMgr.notify(notificationid, notification.build());
    }
}
 
Example 37
Project: xlight_android_native   File: RangeSeekBar.java   Source Code and License 5 votes vote down vote up
/**
 * 计算每个按钮的位置和尺寸
 * Calculates the position and size of each button
 *
 * @param x
 * @param y
 * @param hSize
 * @param parentLineWidth
 * @param cellsMode
 * @param bmpResId
 * @param context
 */
protected void onSizeChanged(int x, int y, int hSize, int parentLineWidth, boolean cellsMode, int bmpResId, Context context) {
    heightSize = hSize;
    widthSize = heightSize ;
    left = x - widthSize / 2;
    right = x + widthSize / 2;
    top = y - heightSize / 2;
    bottom = y + heightSize / 2;

    if (cellsMode) {
        lineWidth = parentLineWidth;
    } else {
        lineWidth = parentLineWidth ;
    }

    if (bmpResId > 0) {
        Bitmap original = BitmapFactory.decodeResource(context.getResources(), bmpResId);

        if (original != null) {
            Matrix matrix = new Matrix();
            float scaleHeight = mThumbSize * 1.0f / original.getHeight();
            float scaleWidth = scaleHeight;
            matrix.postScale(scaleWidth, scaleHeight);
            bmp = Bitmap.createBitmap(original, 0, 0, original.getWidth(), original.getHeight(), matrix, true);
        }

    } else {
        defaultPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        int radius = (int) (widthSize * DEFAULT_RADIUS);
        int barShadowRadius = (int) (radius * 0.95f);
        int mShadowCenterX = widthSize/2;
        int mShadowCenterY = heightSize/2;
        shadowGradient = new RadialGradient(mShadowCenterX, mShadowCenterY, barShadowRadius, Color.BLACK, Color.TRANSPARENT, Shader.TileMode.CLAMP);
    }
}
 
Example 38
Project: Android-Practice   File: ImageResizer.java   Source Code and License 5 votes vote down vote up
/**
 * Calculate an inSampleSize for use in a {@link android.graphics.BitmapFactory.Options} object when decoding
 * bitmaps using the decode* methods from {@link android.graphics.BitmapFactory}. This implementation calculates
 * the closest inSampleSize that is a power of 2 and will result in the final decoded bitmap
 * having a width and height equal to or larger than the requested width and height.
 *
 * @param options An options object with out* params already populated (run through a decode*
 *            method with inJustDecodeBounds==true
 * @param reqWidth The requested width of the resulting bitmap
 * @param reqHeight The requested height of the resulting bitmap
 * @return The value to be used for inSampleSize
 */
public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    // BEGIN_INCLUDE (calculate_sample_size)
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }

        // This offers some additional logic in case the image has a strange
        // aspect ratio. For example, a panorama may have a much larger
        // width than height. In these cases the total pixels might still
        // end up being too large to fit comfortably in memory, so we should
        // be more aggressive with sample down the image (=larger inSampleSize).

        long totalPixels = width * height / inSampleSize;

        // Anything more than 2x the requested pixels we'll sample down further
        final long totalReqPixelsCap = reqWidth * reqHeight * 2;

        while (totalPixels > totalReqPixelsCap) {
            inSampleSize *= 2;
            totalPixels /= 2;
        }
    }
    return inSampleSize;
    // END_INCLUDE (calculate_sample_size)
}
 
Example 39
Project: codedemos   File: BitmapUtil.java   Source Code and License 5 votes vote down vote up
public static Bitmap getRotatedImg(String path) {
    int angle = getBitmapRotation(path);
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    Bitmap bitmap = BitmapFactory.decodeFile(path);
    try {
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bitmap;
}
 
Example 40
Project: AndroidBackendlessChat   File: CircleImageView.java   Source Code and License 5 votes vote down vote up
public void loadFromFile(final String path){
    new Thread(new Runnable() {
        @Override
        public void run() {
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            Message message = new Message();
            message.obj = bitmap;
            handler.sendMessage(message);
        }
    }).start();
}
 
Example 41
Project: custode   File: CustodeUtils.java   Source Code and License 5 votes vote down vote up
/** Restituisce l'immagine del contatto per un numero di telefono. */
public static Bitmap getContactPhoto(Context context, String phoneNumber) {
    ContentResolver contentResolver = context.getContentResolver();
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    String[] projection = new String[] {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID};

    Cursor cursor = contentResolver.query(uri, projection, null, null, null);

    String contactId;
    if (cursor != null && cursor.moveToFirst()) {
        contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
        cursor.close();
    }
    else
        return null;

    Bitmap photo = null;
    try {
        InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),
                ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.valueOf(contactId)));
        if (inputStream != null) {
            photo = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        }
    } catch (IOException ignored) {

    }
    return photo;
}
 
Example 42
Project: SciChart.Android.Examples   File: ColumnChartFillFragment.java   Source Code and License 5 votes vote down vote up
@Override
protected void initExample() {
    texture = BitmapFactory.decodeResource(getResources(), R.drawable.scichartlogo);

    final SpinnerStringAdapter seriesTypeAdapter = new SpinnerStringAdapter(getActivity(), R.array.fill_list);
    fillSpinner.setAdapter(seriesTypeAdapter);
    fillSpinner.setSelection(0);

    final SpinnerStringAdapter seriesMappingAdapter = new SpinnerStringAdapter(getActivity(), R.array.texture_mapping_mode_list);
    textureMappingModesSpinner.setAdapter(seriesMappingAdapter);
    textureMappingModesSpinner.setSelection(0);

    xAxis = sciChartBuilder.newNumericAxis().withGrowBy(new DoubleRange(0.1d, 0.1d)).build();
    yAxis = sciChartBuilder.newNumericAxis().withGrowBy(new DoubleRange(0.1d, 0.1d)).build();

    final XyDataSeries<Double, Double> dataSeries = new XyDataSeries<>(Double.class, Double.class);
    dataSeries.append(new Double[]{0d, 2d, 4d, 6d, 8d, 10d}, new Double[]{1d, 5d, -5d, -10d, 10d, 3d});
    rs = sciChartBuilder.newColumnSeries().withDataSeries(dataSeries).withStrokeStyle(ColorUtil.White, 3f, false).build();

    surface.getChartModifiers().add(sciChartBuilder.newModifierGroupWithDefaultModifiers().build());

    Collections.addAll(surface.getXAxes(), xAxis);
    Collections.addAll(surface.getYAxes(), yAxis);
    Collections.addAll(surface.getRenderableSeries(), rs);

    surface.zoomExtents();
}
 
Example 43
Project: XDisplay   File: Util.java   Source Code and License 5 votes vote down vote up
public static Bitmap decodeSampledBitmapFromPath(String path, int width,int height){
    // 获得图片的宽和高,并不把图片加载到内存中
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    options.inSampleSize = ImageSizeUtil.caculateInSampleSize(options,
            width, height);

    // 使用获得到的InSampleSize再次解析图片
    options.inJustDecodeBounds = false;
    Bitmap bitmap = BitmapFactory.decodeFile(path, options);
    return bitmap;
}
 
Example 44
Project: homeDash   File: HomeDashService.java   Source Code and License 5 votes vote down vote up
public void startForeground(){
    Intent notificationIntent = new Intent(this, HomeDashService.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Notification notification = new Notification.Builder(this)
            .setContentTitle(getText(R.string.homedash_service_notification_title))
            .setContentText(getText(R.string.homedash_service_notification_message))
            .setSmallIcon(R.drawable.ic_home_white_24dp)
            .setLargeIcon(BitmapFactory.decodeResource(getApplication().getResources(),R.mipmap.ic_launcher))
            .setContentIntent(pendingIntent)
            .setLocalOnly(true)
            .build();

    startForeground(ONGOING_NOTIFICATION_ID, notification);
}
 
Example 45
Project: DailyStudy   File: NotificationActivity.java   Source Code and License 5 votes vote down vote up
private void largeText() {
    Notification notification = new NotificationCompat.Builder(this)
            .setStyle(new NotificationCompat.BigTextStyle().bigText("you are good boy!" +
                    "you are good boy!you are good boy!you are good boy!you are good boy!")) // 大文本
            .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))) // 大图片
            .setPriority(NotificationCompat.PRIORITY_MAX) // 设置通知的重要程度
            .build();
}
 
Example 46
Project: Show_Chat   File: AddGroupActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    ((ItemFriendHolder) holder).txtName.setText(listFriend.getListFriend().get(position).name);
    ((ItemFriendHolder) holder).txtEmail.setText(listFriend.getListFriend().get(position).email);
    String avata = listFriend.getListFriend().get(position).avata;
    final String id = listFriend.getListFriend().get(position).id;
    if (!avata.equals(StaticConfig.STR_DEFAULT_BASE64)) {
        byte[] decodedString = Base64.decode(avata, Base64.DEFAULT);
        ((ItemFriendHolder) holder).avata.setImageBitmap(BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length));
    }else{
        ((ItemFriendHolder) holder).avata.setImageBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.default_avata));
    }
    ((ItemFriendHolder) holder).checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (b) {
                listIDChoose.add(id);
                listIDRemove.remove(id);
            } else {
                listIDRemove.add(id);
                listIDChoose.remove(id);
            }
            if (listIDChoose.size() >= 2) {
                btnAddGroup.setBackgroundColor(context.getResources().getColor(R.color.colorPrimary));
            } else {
                btnAddGroup.setBackgroundColor(context.getResources().getColor(R.color.grey_500));
            }
        }
    });
    if (isEdit && editGroup.member.contains(id)) {
        ((ItemFriendHolder) holder).checkBox.setChecked(true);
    }else if(editGroup != null && !editGroup.member.contains(id)){
        ((ItemFriendHolder) holder).checkBox.setChecked(false);
    }
}
 
Example 47
Project: NightSkyGuide   File: DetailFragment.java   Source Code and License 5 votes vote down vote up
private Bitmap loadConstImage(String filename) {
    try {
        // get input stream
        InputStream ims = getActivity().getAssets().open(filename);
        //Drawable constImg = Drawable.createFromStream(ims, null);
        Bitmap constImage = BitmapFactory.decodeStream(ims);
        ims.close();
        return constImage;
    } catch (Exception e) {
        Toast.makeText(getActivity(), "error", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
    return constImage;
}
 
Example 48
Project: Hotspot-master-devp   File: BitmapCommonUtils.java   Source Code and License 5 votes vote down vote up
public static int[] getImageSize(String filePath) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath,options);
    int[] size = new int[2];
    size[0] = options.outWidth;
    size[1] = options.outHeight;
    return size;
}
 
Example 49
Project: QuanMinTV   File: FriendListItem.java   Source Code and License 5 votes vote down vote up
public FriendListItem(Context context, float ratio) {
	super(context);
	int itemPadding = (int) (ratio * DESIGN_ITEM_PADDING);
	setPadding(itemPadding, 0, itemPadding, 0);
	setMinimumHeight((int) (ratio * DESIGN_ITEM_HEIGHT));
	setBackgroundColor(0xffffffff);

	ivCheck = new ImageView(context);
	LayoutParams lp = new LayoutParams(
			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	lp.gravity = Gravity.CENTER_VERTICAL;
	addView(ivCheck, lp);

	aivIcon = new AsyncImageView(context);
	int avatarWidth = (int) (ratio * DESIGN_AVATAR_WIDTH);
	lp = new LayoutParams(avatarWidth, avatarWidth);
	lp.gravity = Gravity.CENTER_VERTICAL;
	int avatarMargin = (int) (ratio * DESIGN_AVATAR_PADDING);
	lp.setMargins(avatarMargin, 0, avatarMargin, 0);
	addView(aivIcon, lp);

	tvName = new TextView(context);
	tvName.setTextColor(0xff000000);
	tvName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
	tvName.setSingleLine();
	lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	lp.gravity = Gravity.CENTER_VERTICAL;
	lp.weight = 1;
	addView(tvName, lp);

	int resId = ResHelper.getBitmapRes(context, "ssdk_oks_classic_check_checked");
	if (resId > 0) {
		bmChd = BitmapFactory.decodeResource(context.getResources(), resId);
	}
	resId = ResHelper.getBitmapRes(getContext(), "ssdk_oks_classic_check_default");
	if (resId > 0) {
		bmUnch = BitmapFactory.decodeResource(context.getResources(), resId);
	}
}
 
Example 50
Project: godlibrary   File: FileUtils.java   Source Code and License 5 votes vote down vote up
public File getResourceFile(String dirsName, String fileName, int resourcesId, int inSampleSize) {
    boolean b = isFileExist(dirsName, fileName);
    if (!b) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = inSampleSize;
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourcesId, options);
        File file = saveBitmap(dirsName, fileName, bitmap);
        scannerFile(file.getPath());
    }
    return getFile(dirsName, fileName);
}
 
Example 51
Project: studydemo   File: UtilTools.java   Source Code and License 5 votes vote down vote up
public static void getImageToShare(Context mContext, ImageView imageView) {
    //1.拿到string
    String imgString = ShareUtil.getString(mContext, "image_title", "");
    if (!imgString.equals("")) {
        //2.利用Base64将我们string转换
        byte[] byteArray = Base64.decode(imgString, Base64.DEFAULT);
        ByteArrayInputStream byStream = new ByteArrayInputStream(byteArray);
        //3.生成bitmap
        Bitmap bitmap = BitmapFactory.decodeStream(byStream);
        imageView.setImageBitmap(bitmap);
    }
}
 
Example 52
Project: ImageLoaderSupportGif   File: ImageFileUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 根据文件内容 判断是否是gif图片
 * @param path
 * @return
 */
public static boolean isGifImageByFile(final String path) {
    if (TextUtils.isEmpty(path))
        return false;

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    final String mime = options.outMimeType;
    return TextUtils.isEmpty(mime) ? false : mime.toLowerCase().endsWith("gif");
}
 
Example 53
Project: GitHub   File: Downsampler.java   Source Code and License 5 votes vote down vote up
private static Bitmap decodeStream(InputStream is, BitmapFactory.Options options,
    DecodeCallbacks callbacks) throws IOException {
  if (options.inJustDecodeBounds) {
    is.mark(MARK_POSITION);
  } else {
    // Once we've read the image header, we no longer need to allow the buffer to expand in
    // size. To avoid unnecessary allocations reading image data, we fix the mark limit so that it
    // is no larger than our current buffer size here. We need to do so immediately before
    // decoding the full image to avoid having our mark limit overridden by other calls to
    // markand reset. See issue #225.
    callbacks.onObtainBounds();
  }
  // BitmapFactory.Options out* variables are reset by most calls to decodeStream, successful or
  // otherwise, so capture here in case we log below.
  int sourceWidth = options.outWidth;
  int sourceHeight = options.outHeight;
  String outMimeType = options.outMimeType;
  final Bitmap result;
  TransformationUtils.getBitmapDrawableLock().lock();
  try {
    result = BitmapFactory.decodeStream(is, null, options);
  } catch (IllegalArgumentException e) {
    throw newIoExceptionForInBitmapAssertion(e, sourceWidth, sourceHeight, outMimeType, options);
  } finally {
    TransformationUtils.getBitmapDrawableLock().unlock();
  }

  if (options.inJustDecodeBounds) {
    is.reset();

  }
  return result;
}
 
Example 54
Project: editor-sql   File: FeThumbUtils.java   Source Code and License 5 votes vote down vote up
private static Bitmap getImageThumbnail(String imagePath, int width, int height) {
    Bitmap bitmap = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    try {
        bitmap = BitmapFactory.decodeFile(imagePath, options);

        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / width;
        int beHeight = h / height;
        int be;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        options.inJustDecodeBounds = false;

        bitmap = BitmapFactory.decodeFile(imagePath, options);
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    } catch (OutOfMemoryError e) {
        if (bitmap != null) {
            bitmap.recycle();
        }
    }

    return bitmap;
}
 
Example 55
Project: sctalk   File: PickPhotoActivity.java   Source Code and License 5 votes vote down vote up
/**
 * 初始化数据
 */
private void initData() {
    Bundle bundle =  getIntent().getExtras();
    currentSessionKey = bundle.getString(IntentConstant.KEY_SESSION_KEY);
    helper = AlbumHelper.getHelper(getApplicationContext());
    dataList = helper.getImagesBucketList(true);
    bimap = BitmapFactory.decodeResource(getResources(),
            R.drawable.tt_default_album_grid_image);
}
 
Example 56
Project: Pocket-Plays-for-Twitch   File: Service.java   Source Code and License 5 votes vote down vote up
/**
 * Gets Bitmap from the specified URL
 * Must not be called on Main UI Thread
 */
public static Bitmap getBitmapFromUrl(String url) {
	Bitmap bitmap = null;

	try {
		HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
		connection.connect();
		InputStream input = connection.getInputStream();
		bitmap = BitmapFactory.decodeStream(input);
	} catch (IOException e) {
		e.printStackTrace();
	}

	return bitmap;
}
 
Example 57
Project: YiZhi   File: PersonalUpperPresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void onStart() {
    //此处实际应用中替换成服务器拉取图片
    Uri headUri = Uri.fromFile(new File(mIView.getActivity().getCacheDir(), HEAD_IMAGE_NAME +
            ".jpg"));
    if (headUri != null) {
        String cropImagePath = FileUtils.getRealFilePathFromUri(AppUtils.getContext(), headUri);
        Bitmap bitMap = BitmapFactory.decodeFile(cropImagePath);
        if (bitMap != null)
            mIView.showHead(bitMap);
    }
}
 
Example 58
Project: Hotspot-master-devp   File: CompressImage.java   Source Code and License 5 votes vote down vote up
public static Bitmap.CompressFormat getImgFormat(BitmapFactory.Options options) {
    String type = options.outMimeType;
    if (type != null && type.indexOf("png") > -1)
        return Bitmap.CompressFormat.PNG;
    else
        return Bitmap.CompressFormat.JPEG;
}
 
Example 59
Project: BBSSDK-for-Android   File: EmojiManager.java   Source Code and License 5 votes vote down vote up
public Bitmap getEmoji(String key) {
	String dir = getEmojiDir(key);
	if (StringUtils.isEmpty(dir)) {
		return null;
	}
	InputStream is = null;
	try {
		is = MobSDK.getContext().getResources().getAssets().open(dir);
		return BitmapFactory.decodeStream(is);
	} catch (IOException e) {
	}
	return null;
}
 
Example 60
Project: browser   File: BitmapUtil.java   Source Code and License 5 votes vote down vote up
public static Bitmap loadFromFile(String filename) {
	try {
		File f = new File(filename);
		if (!f.exists()) {
			return null;
		}
		Bitmap tmp = BitmapFactory.decodeFile(filename);
		// tmp = setExifInfo(filename, tmp);
		return tmp;
	} catch (Exception e) {
		return null;
	}

}