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; }
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; }
/** * <根据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; }
/** 从缓存中获取图片 * */ 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; }
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 ""; }
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(); } }
/** * 以屏幕宽度为基准,显示图片 * * @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; }
/** * 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
/** 检查图片是否超过一定值,是则缩小 */ 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 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; }
// 同比缩放解决方案---图片按比例大小压缩方法(根据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); // 压缩好比例大小后再进行质量压缩 }
/** * コンストラクタ * * @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(); }
/** * 通过资源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); }
/** 获取优化位图 */ 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; }
/** * * 根据资源文件获取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; }
/** * 从资源文件中读取 * * @param context * @param resId * @return */ public static Bitmap createBitmapFromRes(Context context, int resId) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Config.ARGB_8888; opt.inPurgeable = true; opt.inInputShareable = true; InputStream is = context.getResources().openRawResource(resId); return BitmapFactory.decodeStream(is, null, opt); // InputStream is = context.getResources().openRawResource(resId); // return getBitmapByStream(is); }
/** * 加载图片,缩小多少倍 * * @param context * @param id * @return */ public static Bitmap getDecodeBitmapCompress(Context context, int id, int time) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inSampleSize = time; opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; // 获取资源图片 InputStream is = context.getResources().openRawResource(id); return BitmapFactory.decodeStream(is, null, opt); }
/** * Return bitmap through by resources. * * @param res * @param is * @param width * @param height * @return bitmap */ public static Bitmap getBitmap(InputStream is, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inTempStorage = new byte[TEMP_STORAGE_SIZE]; options.inPreferredConfig = Bitmap.Config.RGB_565; options.inPurgeable = true; options.inInputShareable = true; options.inSampleSize = calculateInSampleSize(options, width, height); options.inJustDecodeBounds = false; return BitmapFactory.decodeStream(is, null, options); }
public Bitmap getBitmapResource() { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.ARGB_8888; opt.inPurgeable = true; opt.inInputShareable = true; InputStream is = mCtx.getResources().openRawResource(resid); // get image resource return BitmapFactory.decodeStream(is, null, opt); }
public Jpeg(Activity a, String in_file_name, int quality, String out_file_name) { if (!root_dir.exists()) root_dir.mkdir(); this.a = a; String string = new String(); inFile = new File(in_file_name); if (in_file_name.endsWith(".jpg") && !in_file_name.endsWith(".tif") && !in_file_name.endsWith(".gif")) { StandardUsage(); } if (out_file_name == null) { string = inFile.getName().substring(0, inFile.getName().lastIndexOf(".")) + ".jpg"; } else { string = out_file_name; if (string.endsWith(".tif") || string.endsWith(".gif")) { string = string.substring(0, string.lastIndexOf(".")); } if (!string.endsWith(".jpg")) { string = string.concat(".jpg"); } } outFile = new File(root_dir, string); if (inFile.exists()) { try { dataOut = new FileOutputStream(outFile); } catch (final IOException e) { Log.e(LOG, e.toString()); e.printStackTrace(); } Quality = quality; opts = new BitmapFactory.Options(); opts.inDither = false; opts.inPurgeable = true; opts.inInputShareable = true; opts.inTempStorage = new byte[32 * 1024]; // image = BitmapFactory.decodeFile(in_file_name, opts); image = BitmapFactory.decodeFile(in_file_name); jpg = new JpegEncoder(image, Quality, dataOut, ""); } else { // TODO: could not find the in file-- throw error Log.e(LOG, "could not find the inFile? (" + inFile.getAbsolutePath() + ")"); return; } }
/** * 通过简单处理后获取res中的bitmap对象 * * @param paramResources * @param res * @param width 长度 * @param height 高度 * @return bitmap 对象 */ public static Bitmap decodeSampledBitmapFromResource( Resources paramResources, int res, int width, int height) { InputStream localInputStream = paramResources.openRawResource(res); BitmapFactory.Options localOptions = new BitmapFactory.Options(); localOptions.inTempStorage = new byte[TEMP_STORAGE_SIZE]; localOptions.inPreferredConfig = Bitmap.Config.RGB_565; localOptions.inPurgeable = true; localOptions.inInputShareable = true; localOptions.inSampleSize = calculateInSampleSize(localOptions, width, height); localOptions.inJustDecodeBounds = false; return BitmapFactory.decodeStream(localInputStream, null, localOptions); }
/** * 把图片资源文件转换为Bitmap * * @param resId :图片资源文件编号 * @return */ public static Bitmap readBitMap(int resId) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; // opt.inJustDecodeBounds = false; // opt.inSampleSize = 50; // 獲取資源圖片 InputStream is = BaseApplication.getInstance().getApplicationContext().getResources().openRawResource(resId); return BitmapFactory.decodeStream(is, null, opt); }
/** * Return bitmap through by imagePath. * * @param imagePath * @param width * @param height * @return bitmap */ public static Bitmap getBitmap(String imagePath, int width, int height) { if (imagePath == null || "".equals(imagePath)) { return null; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inTempStorage = new byte[TEMP_STORAGE_SIZE]; options.inPreferredConfig = Bitmap.Config.RGB_565; options.inPurgeable = true; options.inInputShareable = true; options.inSampleSize = calculateInSampleSize(options, width, height); options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(imagePath, options); }
private Bitmap getThumbnail(long id) { Bitmap bitmap = null; BitmapFactory.Options options = new BitmapFactory.Options(); options.inDither = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.inScaled = true; options.inJustDecodeBounds = false; options.inPurgeable = true; options.inInputShareable = true; ContentResolver cr = mContext.getContentResolver(); bitmap = MediaStore.Video.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null); return bitmap; }
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; }
@Override protected Boolean doInBackground(Void... params) { // QRCodeClient client = new QRCodeClient(); // For scanning a file from /res folder // InputStream fileInputStream = // getResources().openRawResource(R.drawable.qr_code_test_p); BitmapFactory.Options bfOptions = new BitmapFactory.Options(); bfOptions.inDither = false; // Disable Dithering mode bfOptions.inPurgeable = true; // Tell to gc that whether it needs // free memory, the Bitmap can be // cleared bfOptions.inInputShareable = true; // Which kind of reference will // be used to recover the Bitmap // data after being clear, when // it will be used in the future bfOptions.inTempStorage = new byte[32 * 1024]; Bitmap bMap = BitmapFactory.decodeFile(path, bfOptions); bMap = Bitmap.createScaledBitmap(bMap, 1200, 900, false); // Lets // change // size // to a // bit // smaller, // I // didn't // experiment // a lot // with // it so // it // can // be // not // optimal ByteArrayOutputStream bos = new ByteArrayOutputStream(); bMap.compress(CompressFormat.PNG, 0, bos); byte[] bitmapdata = bos.toByteArray(); ByteArrayInputStream fileInputStream = new ByteArrayInputStream(bitmapdata); BufferedInputStream bis = new BufferedInputStream(fileInputStream); try { // content = client.decode(bis); } catch (Exception e) { e.printStackTrace(); } SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd.MM", java.util.Locale.getDefault()); Date dt = new Date(); date = sdf.format(dt); return true; }
public static Bitmap getSuitableBitmap(Activity act, Uri uri, float ww, float hh) throws FileNotFoundException { BitmapFactory.Options newOpts = new BitmapFactory.Options(); newOpts.inJustDecodeBounds = true; // 只读边,不读内容 Bitmap bitmap = null; bitmap = BitmapFactory.decodeStream(act.getContentResolver().openInputStream(uri), null, newOpts); newOpts.inJustDecodeBounds = false; float w = newOpts.outWidth; float h = newOpts.outHeight; float wwh = 640f; // float hhh = (wwh / w) * h; // int be = 1; if (w > h && w > wwh) { be = (int) (newOpts.outWidth / wwh); } else if (w < h && h > hhh) { be = (int) (newOpts.outHeight / hhh); be += 1; } if (be <= 0) be = 1; newOpts.inSampleSize = be; // 设置采样率 newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888; // 该模式是默认的,可不设 newOpts.inPurgeable = true; // 同时设置才会有效 newOpts.inInputShareable = true; // 。当系统内存不够时候图片自动被回收 bitmap = BitmapFactory.decodeStream(act.getContentResolver().openInputStream(uri), null, newOpts); // return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩 // 其实是无效的,大家尽管尝试 return bitmap; // int maxNumOfPixels = width * height; // BitmapFactory.Options opts = new BitmapFactory.Options(); // opts.inJustDecodeBounds = true; // BitmapFactory.decodeStream(this.getContentResolver().openInputStream(uri), null, // opts); // opts.inSampleSize = computeSampleSize(opts, -1, maxNumOfPixels); // opts.inJustDecodeBounds = false; // try { // return BitmapFactory.decodeStream(this.getContentResolver().openInputStream(uri), // null, // opts); // } catch (OutOfMemoryError err) { // } // return null; }
// 同比缩放解决方案---图片按比例大小压缩方法(根据路径获取图片并压缩) public static Bitmap compressByFilePath( String pathName, int dstWidth, int dstHeight, int sizeInKb, ScalingLogic scalingLogic) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(pathName, 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; bitmap = BitmapFactory.decodeFile(pathName, options); return compressImage(bitmap, sizeInKb); }
/* 图片处理技术 */ public static Bitmap compressImageFromFile(String srcPath, float height, float width) { if (srcPath == null) return null; File file = new File(srcPath); if (!file.exists()) { return null; } 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; int be = 1; int x = 0; int y = 0; if (w > width) { x = (int) (newOpts.outWidth / width); } else if (h > height) { y = (int) (newOpts.outHeight / height); } be = x > y ? x : y; if (be <= 0) be = 1; newOpts.inSampleSize = be; // 设置采样率 newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888; // 该模式是默认的,可不设 newOpts.inPurgeable = true; // 同时设置才会有效 newOpts.inInputShareable = true; // 。当系统内存不够时候图片自动被回收 bitmap = BitmapFactory.decodeFile(srcPath, newOpts); FileOutputStream out = null; try { out = new FileOutputStream(file); if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) { out.flush(); out.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; }
private static final Bitmap getBitmapByBytes( byte[] bytes, BitmapFactory.Options options, int sampleSize) { Bitmap result = null; if (bytes != null && bytes.length > 0) { try { options.inSampleSize = sampleSize; options.inJustDecodeBounds = false; options.inPurgeable = true; options.inInputShareable = true; options.inPreferredConfig = Bitmap.Config.RGB_565; result = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options); } catch (OutOfMemoryError e) { e.printStackTrace(); } } return result; }