@Override public void run() { int len = mFiles.size(); for (int i = 0; i < len; i++) { if (mStop) { mStop = false; mFiles = null; return; } final File file = new File(mDir + "/" + mFiles.get(i)); if (isImageFile(file.getName())) { long len_kb = file.length() / 1024; BitmapFactory.Options options = new BitmapFactory.Options(); options.outWidth = mWidth; options.outHeight = mHeight; if (len_kb > 1000 && len_kb < 5000) { options.inSampleSize = 32; options.inPurgeable = true; mThumb = new SoftReference<Bitmap>(BitmapFactory.decodeFile(file.getPath(), options)); } else if (len_kb >= 5000) { options.inSampleSize = 32; options.inPurgeable = true; mThumb = new SoftReference<Bitmap>(BitmapFactory.decodeFile(file.getPath(), options)); } else if (len_kb <= 1000) { options.inPurgeable = true; mThumb = new SoftReference<Bitmap>( Bitmap.createScaledBitmap( BitmapFactory.decodeFile(file.getPath()), mWidth, mHeight, false)); } mCacheMap.put(file.getPath(), mThumb.get()); mHandler.post( new Runnable() { @Override public void run() { Message msg = mHandler.obtainMessage(); msg.obj = (Bitmap) mThumb.get(); msg.sendToTarget(); } }); } } }
public Bitmap decodeThumbFile(String path) { Bitmap bmp = null; Log.v("File Path", path); File f = new File(path); try { // Decode image size BitmapFactory.Options options = new BitmapFactory.Options(); options.inTempStorage = new byte[16 * 1024]; options.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, options); int IMAGE_MAX_SIZE = 640; int scale = 1; if (options.outHeight > IMAGE_MAX_SIZE || options.outWidth > IMAGE_MAX_SIZE) { scale = (int) Math.pow( 2, (int) Math.round( Math.log( IMAGE_MAX_SIZE / (double) Math.max(options.outHeight, options.outWidth)) / Math.log(0.5))); } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; o2.inPurgeable = true; o2.outHeight = 480; o2.outWidth = 640; Bitmap temp = BitmapFactory.decodeStream(new FileInputStream(f), null, o2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); temp.compress( Bitmap.CompressFormat.PNG, (int) (100 * ImageFileManipulation.IAMGE_COMPRESSION_RATIO), baos); temp.recycle(); temp = null; options = new BitmapFactory.Options(); options.inDither = true; options.inPurgeable = true; options.inInputShareable = true; options.inSampleSize = scale; options.inTempStorage = new byte[32 * 1024]; bmp = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size(), options); } catch (Exception e) { e.printStackTrace(); } return bmp; }
private Bitmap loadResizedImage() { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; decode(options); int scale = 1; while (checkSize( options.outWidth / scale > mOutputWidth, options.outHeight / scale > mOutputHeight)) { scale++; } scale--; if (scale < 1) { scale = 1; } options = new BitmapFactory.Options(); options.inSampleSize = scale; options.inPreferredConfig = Bitmap.Config.RGB_565; options.inPurgeable = true; options.inTempStorage = new byte[32 * 1024]; Bitmap bitmap = decode(options); if (bitmap == null) { return null; } bitmap = rotateImage(bitmap); bitmap = scaleBitmap(bitmap); return bitmap; }
/** * Create and returns the Bitmap image from local storage optimized by size * * @param imageID - filename of the image * @param reqSize - maximum side of image returns default image (DEFAULT_IMAGE_NAME) if image * can't be loaded used in ArticleViewAdapter.getView() */ public static Bitmap getBitmapFromStorage(Context context, String imageID, int reqSize) { Log.d(TAG, ".getBitmapFromFilePath(), image=" + imageID + ", size=" + reqSize); Bitmap result = null; // construct full file name String fileName = imageID + JPEG_SUFFIX; File imageFile = new File(context.getExternalFilesDir(Utils.TYPE_PICTURE), fileName); // if image file exists trying to load, optimize and decode if (imageFile.exists()) { // First decode with inJustDecodeBounds=true to check dimensions BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(imageFile.getAbsolutePath(), bmOptions); // Calculate inSampleSize bmOptions.inSampleSize = calculateImageInSampleSize(bmOptions, reqSize, reqSize); // Decode bitmap with inSampleSize set from file with given options bmOptions.inJustDecodeBounds = false; bmOptions.inPurgeable = true; result = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), bmOptions); } // if can't be loaded and decoded, load default image from local storage instead if (result == null) { Log.d(TAG, ".getBitmapFromFilePath(), cann't decode image:" + imageFile.getAbsolutePath()); File file = new File(context.getExternalFilesDir(TYPE_PICTURE), DEFAULT_IMAGE_NAME); result = BitmapFactory.decodeFile(file.getAbsolutePath()); } return result; }
public static String get450File(String mStrPicPath) { int angel = UtilImage.readPictureDegree(mStrPicPath); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile(mStrPicPath, options); bmp = null; options.inJustDecodeBounds = false; options.inPreferredConfig = Bitmap.Config.RGB_565; options.inPurgeable = true; options.inInputShareable = true; int scale = 1; if (options.outWidth > UtilFile.BITMAP_WIDTH_SHOW) scale = (int) (options.outWidth / UtilFile.BITMAP_WIDTH_SHOW); options.inSampleSize = scale; bmp = BitmapFactory.decodeFile(mStrPicPath, options); /** 把图片旋转为正的方向 */ bmp = UtilImage.rotaingImageView(angel, bmp); String str_dir = UtilFile.getFolderPath(UtilFile.DIR_PHOTO_CACHE); File dir = new File(str_dir); File filepic = new File(dir, System.currentTimeMillis() + ".jpg"); try { bmp.compress(CompressFormat.JPEG, 100, new FileOutputStream(filepic)); } catch (FileNotFoundException e) { e.printStackTrace(); } // 回收bitmap recycleBitmap(bmp); if (filepic != null) return filepic.toString(); return ""; }
/* Helper to avoid Out of Memory Exception */ private Bitmap getPic(int width, int height, String imagePath) { int maxWidth = context.getResources().getDisplayMetrics().widthPixels; // Get the dimensions of the View int targetW = (maxWidth / 3) - 10; // Get the dimensions of the bitmap BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(imagePath, bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; // Determine how much to scale down the image int scaleFactor = Math.min(photoW / targetW, photoH / targetW); // Decode the image file into a Bitmap sized to fill the View bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor; bmOptions.inPurgeable = true; Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions); if (bitmap == null) Log.e("Simba", "bitmap is NULL"); return bitmap; }
public Bitmap getImageBitmap(String value) { URL imageUrl = null; Bitmap bitmap = null; System.out.println("menulist_imageurl===" + value); if (value == null) return null; try { imageUrl = new URL(value); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); imgis = is; BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; // bitmap = BitmapFactory.decodeStream(is); bitmap = BitmapFactory.decodeStream(is, null, opt); } catch (Exception ex) { ex.printStackTrace(); } return bitmap; }
public static Bitmap getOptionBitmap(File imgFile, int tw, int th) { if (imgFile == null || !imgFile.exists() || !imgFile.isFile()) return null; // Get the dimensions of the View // int targetW = mImageView.getMeasuredWidth(); // int targetH = mImageView.getMeasuredHeight(); int targetW = tw; int targetH = th; // Get the dimensions of the bitmap BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(imgFile.getAbsolutePath(), bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; // Determine how much to scale down the image int scaleFactor = Math.max(photoW / targetW, photoH / targetH); // Decode the image file into a Bitmap sized to fill the View bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor; bmOptions.inPurgeable = true; Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), bmOptions); return bitmap; }
/** * コンストラクタ * * @param context */ public OverlayFigureView(Context context, String seqDir, int fgCount) { super(context); // ビットマップ展開オプションを設定 mOpt.inJustDecodeBounds = false; mOpt.inPurgeable = true; mOpt.inInputShareable = true; mOpt.outHeight = STAMP_HEIGHT; mOpt.outWidth = STAMP_WIDTH; mOpt.inSampleSize = 1; // OpenCV設定用 mCvGaussianSize = new Size(1, 1); setFocusable(true); // gestureを作成(設定はview内) mGListener = new MyGestureListener(this); mGesture = new GestureDetector(mGListener); mScaleListener = new MyScaleGestureListener(); scaleGesture = new ScaleGestureDetector(context, mScaleListener); // フォルダ設定 mDirectory = seqDir; // フィギュア枚数 mFgCount = fgCount; mContext = context; // ビットマップ作成 createFigureBitmap(); }
public static Bitmap getScaleOptionImageByScaleOfWinWidth( Context context, File imgFile, float scaleOfWinWidth) { if (imgFile == null) return null; BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(imgFile.getAbsolutePath(), bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; if (photoW == 0) { return null; } int th = (int) (DeviceUtil.getDeviceHeight(context)); int tw = (int) (DeviceUtil.getDeviceWidth(context)); tw = (int) (tw * scaleOfWinWidth); if (tw == 0) { return null; } th = (int) (tw * ((double) photoH / photoW)); int scaleFactor = Math.min(photoW / tw, photoH / th); bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor; bmOptions.inPurgeable = true; Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), bmOptions); return bitmap; }
/** * download image from url through the Internet * * @param url * @return Bitmap from http */ private Bitmap getImageHttp(String url) { // try to get image from file cache // Logger.debug(this, "Load image from network " + url); Bitmap bitmap; int times = 0; while (times < IMAGE_RETRY_TIMES) { try { URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoInput(true); conn.connect(); InputStream inputStream = conn.getInputStream(); BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; InputStream is = new FlushedInputStream(inputStream); bitmap = BitmapFactory.decodeStream(is, null, opt); is.close(); inputStream.close(); return bitmap; } catch (Exception e) { Logger.w("getImageHttp=" + url + e); times++; } continue; } return null; } // end of downloadBitmap
/** * 以屏幕宽度为基准,显示图片 * * @return */ public static Bitmap decodeStream(Context context, Intent data, float size) { Bitmap image = null; try { Uri dataUri = data.getData(); // 获取原图宽度 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inPurgeable = true; options.inInputShareable = true; BitmapFactory.decodeStream( context.getContentResolver().openInputStream(dataUri), null, options); // 计算缩放比例 float reSize = (int) (options.outWidth / size); if (reSize <= 0) { reSize = 1; } Log.d(TAG, "old-w:" + options.outWidth + ", llyt-w:" + size + ", resize:" + reSize); // 缩放 options.inJustDecodeBounds = false; options.inSampleSize = (int) reSize; image = BitmapFactory.decodeStream( context.getContentResolver().openInputStream(dataUri), null, options); } catch (Exception e) { e.printStackTrace(); } return image; }
private void setPic() { // Get the dimensions of the View int targetW = mImageView.getWidth(); int targetH = mImageView.getHeight(); // Get the dimensions of the bitmap BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; // Determine how much to scale down the image int scaleFactor = Math.min(photoW / targetW, photoH / targetH); // Decode the image file into a Bitmap sized to fill the View bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor; bmOptions.inPurgeable = true; Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); mImageView.setImageBitmap(bitmap); Intent intent = new Intent(this, CropImageActivity.class); // intent.putExtra("bitmap", bitmap); MyApplication application = (MyApplication) getApplication(); application.mBitmap = bitmap; startActivity(intent); String directoryDcim = Environment.DIRECTORY_DCIM; }
/** 从缓存中获取图片 * */ public Bitmap getImage(final String url) { final String path = getDirectory() + "/" + convertUrlToFileName(url); File file = new File(path); if (file.exists()) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; // 获取资源图片 FileInputStream fis; try { fis = new FileInputStream(path); Bitmap bmp = BitmapFactory.decodeStream(fis, null, opt); if (bmp == null) { file.delete(); } else { updateFileTime(path); return bmp; } } catch (FileNotFoundException e) { e.printStackTrace(); } } return null; }
private final Bitmap compress(String uri, int reqWidth, int reqHeight) { Bitmap bitmap = null; try { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeFile(uri, opts); int height = opts.outHeight; int width = opts.outWidth; int inSampleSize = 1; if (width > height && width > reqWidth) { inSampleSize = Math.round((float) width / (float) reqWidth); } else if (height > width && height > reqHeight) { inSampleSize = Math.round((float) height / (float) reqHeight); } if (inSampleSize <= 1) inSampleSize = 1; opts.inSampleSize = inSampleSize; opts.inJustDecodeBounds = false; opts.inPreferredConfig = Config.RGB_565; opts.inPurgeable = true; opts.inInputShareable = true; opts.inTargetDensity = getResources().getDisplayMetrics().densityDpi; opts.inScaled = true; opts.inTempStorage = new byte[16 * 1024]; bitmap = BitmapFactory.decodeStream(new BufferedInputStream(new FileInputStream(uri)), null, opts); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } return bitmap; }
// 图片压缩 private Bitmap compressImageFromFile(String srcPath) { BitmapFactory.Options newOpts = new BitmapFactory.Options(); newOpts.inJustDecodeBounds = true; // 只读边,不读内容 Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts); newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; float hh = 800f; // float ww = 480f; // int be = 1; if (w > h && w > ww) { be = (int) (newOpts.outWidth / ww); } else if (w < h && h > hh) { be = (int) (newOpts.outHeight / hh); } if (be <= 0) be = 1; newOpts.inSampleSize = be; // 设置采样率 newOpts.inPreferredConfig = Config.ARGB_8888; // 该模式是默认的,可不设 newOpts.inPurgeable = true; // 同时设置才会有效 newOpts.inInputShareable = true; // 。当系统内存不够时候图片自动被回收 bitmap = BitmapFactory.decodeFile(srcPath, newOpts); // return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩 // 其实是无效的,大家尽管尝试 return bitmap; }
/** * <根据URL下载图片,并保存到本地> <功能详细描述> * * @param imageURL * @param context * @return * @see [类、类#方法、类#成员] */ public static Bitmap loadImageFromUrl(String imageURL, File file, Context context) { Bitmap bitmap = null; try { URL url = new URL(imageURL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); con.connect(); if (con.getResponseCode() == 200) { InputStream inputStream = con.getInputStream(); FileUtil.deleteDirectory(FileSystemManager.getUserHeadPath(context, Global.getUserId())); ByteArrayOutputStream OutputStream = new ByteArrayOutputStream(); FileOutputStream out = new FileOutputStream(file.getPath()); byte buf[] = new byte[1024 * 20]; int len = 0; while ((len = inputStream.read(buf)) != -1) { OutputStream.write(buf, 0, len); } OutputStream.flush(); OutputStream.close(); inputStream.close(); out.write(OutputStream.toByteArray()); out.close(); BitmapFactory.Options imageOptions = new BitmapFactory.Options(); imageOptions.inPreferredConfig = Bitmap.Config.RGB_565; imageOptions.inPurgeable = true; imageOptions.inInputShareable = true; bitmap = BitmapFactory.decodeFile(file.getPath(), imageOptions); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; }
// 同比缩放解决方案---图片按比例大小压缩方法(根据Bitmap图片压缩) public static Bitmap compressByBitmap( Bitmap srcBitmap, int dstWidth, int dstHeight, int sizeInKb, ScalingLogic scalingLogic) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); int quality = 100; while (baos.toByteArray().length / 1024 > 1024) { // 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出 baos.reset(); // 重置baos即清空baos srcBitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos); // 这里压缩quality%,把压缩后的数据存放到baos中 quality -= 10; // 每次都减少10 } ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); BitmapFactory.Options options = new BitmapFactory.Options(); // 开始读入图片,此时把options.inJustDecodeBounds 设回true了 options.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeStream(bais, null, options); int inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight, scalingLogic); options.inSampleSize = inSampleSize > 0 ? inSampleSize : 1; // 设置缩放比例 options.inJustDecodeBounds = false; options.inPreferredConfig = Bitmap.Config.RGB_565; options.inPurgeable = true; options.inInputShareable = true; // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了 bais = new ByteArrayInputStream(baos.toByteArray()); bitmap = BitmapFactory.decodeStream(bais, null, options); return compressImage(bitmap, sizeInKb); // 压缩好比例大小后再进行质量压缩 }
private void setPic() { /* There isn't enough memory to open up more than a couple camera photos */ /* So pre-scale the target bitmap into which the file is decoded */ /* Get the size of the ImageView */ int targetW = mImageView.getWidth(); int targetH = mImageView.getHeight(); /* Get the size of the image */ BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; /* Figure out which way needs to be reduced less */ int scaleFactor = 1; if ((targetW > 0) || (targetH > 0)) { scaleFactor = Math.min(photoW / targetW, photoH / targetH); } /* Set bitmap options to scale the image decode target */ bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor; bmOptions.inPurgeable = true; /* Decode the JPEG file into a Bitmap */ Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); /* Associate the Bitmap to the ImageView */ mImageView.setImageBitmap(bitmap); mImageView.setVisibility(View.VISIBLE); }
private Bitmap handleImage(String imagePath) { BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmapOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(imagePath, bitmapOptions); // set bitmap options to scale the image decode target bitmapOptions.inJustDecodeBounds = false; bitmapOptions.inSampleSize = 4; bitmapOptions.inPurgeable = true; // decode the JPEG file into a bitmap Bitmap originalBitmap = null; Bitmap bitmap = null; try { originalBitmap = BitmapFactory.decodeFile(imagePath, bitmapOptions); bitmap = BitmapScaler.scaleToFill(originalBitmap, mImageSize, mImageSize); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (originalBitmap != null) originalBitmap.recycle(); } // handle bitmap rotation int rotation = getBitmapRotation(imagePath); if (rotation > 0) { Matrix matrix = new Matrix(); matrix.setRotate(rotation, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } return bitmap; }
Bitmap scaleToDPSize(File file, int targetW, int targetH) { // Scale The Image // Get the dimensions of the bitmap BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getAbsolutePath(), bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; if (photoH < 150 || photoW < 100) { Toast.makeText(this, "Image Resolution is too small.", Toast.LENGTH_SHORT).show(); return null; } // Determine how much to scale down the image int scaleFactor = Math.min(photoW / targetW, photoH / targetH); // Decode the image file into a Bitmap sized to fill the View bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor; bmOptions.inPurgeable = true; Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), bmOptions); return bitmap; }
public static final Bitmap decodeBitmap(String filePath, int targetW, int targetH) { // Get the dimensions of the bitmap BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; // Determine how much to scale down the image int scaleFactor = Math.min(photoW / targetW, photoH / targetH); // Decode the image file into a Bitmap sized to fill the View bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor; bmOptions.inPurgeable = true; Bitmap src = BitmapFactory.decodeFile(filePath, bmOptions); Matrix matrix = getMatrixForImageOrientation(filePath); if (src != null) { return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true); } return null; }
public static boolean compressBitmapFile( String dstPath, String srcPath, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inPurgeable = true; BitmapFactory.decodeFile(srcPath, options); if (options.outWidth > 0) { if (options.outWidth > reqWidth || options.outHeight > reqHeight) { options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; try { Bitmap bmp = BitmapFactory.decodeFile(srcPath, options); FileHelper.saveBitmapToFile(dstPath, bmp, 90); } catch (OutOfMemoryError e) { e.printStackTrace(); return false; } } else { FileHelper.copyFile(dstPath, srcPath); } } else { return false; } return true; }
/** 检查图片是否超过一定值,是则缩小 */ public static Bitmap convertToThumb(byte[] buffer, float size) { // 获取原图宽度 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inPurgeable = true; options.inInputShareable = true; Bitmap bm = BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options); // 计算缩放比例 float reSize = options.outWidth / size; if (options.outWidth > options.outHeight) { reSize = options.outHeight / size; } if (reSize <= 0) { reSize = 1; } Log.d(TAG, "convertToThumb, reSize:" + reSize); // 缩放 options.inJustDecodeBounds = false; options.inSampleSize = (int) reSize; if (bm != null && !bm.isRecycled()) { bm.recycle(); bm = null; Log.e(TAG, "convertToThumb, recyle"); } bm = BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options); if (bm == null) { Log.e(TAG, "convertToThumb, decode fail:" + null); return null; } return bm; }
private void saveImage(byte[] data) { try { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, opts); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); opts.inSampleSize = calculateInSampleSize(opts, dm.heightPixels, dm.widthPixels); opts.inPurgeable = true; opts.inInputShareable = true; opts.inTempStorage = new byte[64 * 1024]; opts.inJustDecodeBounds = false; Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length, opts); if (bm != null) { bm = Util.rotate(bm, getRotate()); File file = new File(filePath); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); bm.compress(Bitmap.CompressFormat.JPEG, 100, bos); bos.flush(); bos.close(); } } catch (Exception e) { e.printStackTrace(); } }
/** * 通过资源id转化成Bitmap * * @param context * @param resId * @return */ public static Bitmap ReadBitmapById(Context context, int resId) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; InputStream is = context.getResources().openRawResource(resId); return BitmapFactory.decodeStream(is, null, opt); }
// ========================================================================= public static Bitmap setCustomizeImage(ImageView img, String imgPath) { // Get the dimensions of the View /** HOTSPOT BEGIN */ int targetW = img.getWidth(); int targetH = img.getHeight(); // Get the dimensions of the bitmap BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(imgPath, bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; // Determine how much to scale down the image int scaleFactor = Math.min(photoW / targetW, photoH / targetH); // Decode the image file into a Bitmap sized to fill the View bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor; bmOptions.inPurgeable = true; Bitmap bitmap = BitmapFactory.decodeFile(imgPath, bmOptions); // try OutputStream stream; try { stream = new FileOutputStream(imgPath); bitmap.compress(CompressFormat.JPEG, 100, stream); } catch (FileNotFoundException e) { e.printStackTrace(); } // /** HOTSPOT END */ // region Saving Bitmap icon to sdcard icon folder RESERVED CODES FOR CREATING THUMBNAILS // String root = Environment.getExternalStorageDirectory().toString(); // File myDir = new File(root + "/iOTA_Thumbs"); // // if(!myDir.exists()){ // myDir.mkdirs(); // } // // String fname = new File(imgPath).getName(); // // File file = new File (myDir, fname); // // //if (file.exists ()) file.delete (); // try { // FileOutputStream out = new FileOutputStream(file); // bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); // out.flush(); // out.close(); // // } catch (Exception e) { // e.printStackTrace(); // } // endregion return bitmap; }
/** * * 根据资源文件获取Bitmap * * @param context * @param drawableId * @return */ public static Bitmap ReadBitmapById(Context context, int drawableId) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Config.ARGB_8888; options.inInputShareable = true; options.inPurgeable = true; InputStream stream = context.getResources().openRawResource(drawableId); Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options); return bitmap; }
/** 获取优化位图 */ private Bitmap getOptsBitmap(int resId) { InputStream _in = mContext.getResources().openRawResource(resId); BitmapFactory.Options _opts = new Options(); _opts.inInputShareable = true; // _opts.inSampleSize = 2; _opts.inPurgeable = true; Bitmap _map = BitmapFactory.decodeStream(_in, null, _opts); return _map; }
private void setPic() { Log.d("setPic", "Display image " + mCurrentPhotoPath); ImageView imageView = (ImageView) findViewById(R.id.cameraImage); int targetW = imageView.getWidth(); int targetH = imageView.getHeight(); Log.d("setPic", "layout ( " + targetW + " * " + targetH + " )"); Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int height = size.y; Log.d("setPic", "display ( " + width + " * " + height + " )"); imageView.getLayoutParams().width = ((width / 100) * 80); ; imageView.getLayoutParams().height = ((height / 100) * 80); imageView.requestLayout(); targetW = imageView.getWidth(); targetH = imageView.getHeight(); Log.d("setPic", "new layout ( " + targetW + " * " + targetH + " )"); /* // working for local image Bitmap bmp; bmp=BitmapFactory.decodeResource(getResources(),R.drawable.miau);//image is your image bmp=Bitmap.createScaledBitmap(bmp, targetW,targetH, true); imageView.setImageBitmap(bmp); */ // Get the dimensions of the bitmap BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; Log.d("setPic", "photo ( " + photoW + " * " + photoH + " )"); // Determine how much to scale down the image int scaleFactor = Math.min(photoW / targetW, photoH / targetH); // Decode the image file into a Bitmap sized to fill the View bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor; bmOptions.inPurgeable = true; Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); imageView.setImageBitmap(bitmap); }