@SuppressWarnings("unused") public Bitmap getThumbnail(Uri uri, int THUMBNAIL_SIZE) throws FileNotFoundException, IOException { InputStream input = context.getContentResolver().openInputStream(uri); BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options(); onlyBoundsOptions.inJustDecodeBounds = true; onlyBoundsOptions.inDither = true; // optional onlyBoundsOptions.inPreferredConfig = Config.ARGB_8888; // optional BitmapFactory.decodeStream(input, null, onlyBoundsOptions); input.close(); if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) return null; int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth; double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE) : 1.0; BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio); bitmapOptions.inDither = true; // optional bitmapOptions.inPreferredConfig = Config.ARGB_8888; // optional input = context.getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions); int width = bitmap.getWidth(); int height = bitmap.getHeight(); input.close(); return bitmap; }
static { // for the cache, // 565 is faster to decode and display // and we don't want to dither here because the image will be scaled down later sBitmapOptionsCache.inPreferredConfig = Bitmap.Config.RGB_565; sBitmapOptionsCache.inDither = false; sBitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888; sBitmapOptions.inDither = false; }
@Override public Image newImage(String fileName, ImageFormat format) { Bitmap.Config config = null; if (format == ImageFormat.RGB565) config = Bitmap.Config.RGB_565; else if (format == ImageFormat.ARGB4444) config = Bitmap.Config.ARGB_4444; else config = Bitmap.Config.ARGB_8888; BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = config; InputStream in = null; Bitmap bitmap = null; try { in = assets.open(fileName); bitmap = BitmapFactory.decodeStream(in, null, options); if (bitmap == null) throw new RuntimeException("Couldn't load bitmap from asset '" + fileName + "'"); } catch (IOException e) { throw new RuntimeException("Couldn't load bitmap from asset '" + fileName + "'"); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } if (bitmap.getConfig() == Bitmap.Config.RGB_565) format = ImageFormat.RGB565; else if (bitmap.getConfig() == Bitmap.Config.ARGB_4444) format = ImageFormat.ARGB4444; else format = ImageFormat.ARGB8888; return new AndroidImage(bitmap, format); }
/** * Make a bitmap from a given Uri, minimal side length, and maximum number of pixels. The image * data will be read from specified pfd if it's not null, otherwise a new input stream will be * created using specified ContentResolver. * * <p>Clients are allowed to pass their own BitmapFactory.Options used for bitmap decoding. A new * BitmapFactory.Options will be created if options is null. */ private static Bitmap makeBitmap( int minSideLength, int maxNumOfPixels, Uri uri, ContentResolver cr, ParcelFileDescriptor pfd, BitmapFactory.Options options) { Bitmap b = null; try { if (pfd == null) pfd = makeInputStream(uri, cr); if (pfd == null) return null; if (options == null) options = new BitmapFactory.Options(); FileDescriptor fd = pfd.getFileDescriptor(); options.inSampleSize = 1; options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fd, null, options); if (options.mCancel || options.outWidth == -1 || options.outHeight == -1) { return null; } options.inSampleSize = computeSampleSize(options, minSideLength, maxNumOfPixels); options.inJustDecodeBounds = false; options.inDither = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; b = BitmapFactory.decodeFileDescriptor(fd, null, options); } catch (OutOfMemoryError ex) { Log.e(TAG, "Got oom exception ", ex); return null; } finally { closeSilently(pfd); } return b; }
static Button load( Context context, int id, int resId, boolean landscape, boolean is565, Rect screen, Rect space, boolean forceLoad) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final String prefLayoutBase = "Controls." + (landscape ? "Landscape." : "Portrait."); final String prefBase = prefLayoutBase + getButtonName(id) + "."; final Button template = landscape ? landscapeToDefault.get(id) : portraitToDefault.get(id); if (forceLoad || prefs.getBoolean(prefLayoutBase + "Draw", true)) { float controlxscale = (float) screen.width() / (float) space.width(); float controlyscale = (float) screen.height() / (float) space.height(); final Rect finalRect = new Rect( prefs.getInt(prefBase + "Left", (int) (template.position.left * controlxscale)), prefs.getInt(prefBase + "Top", (int) (template.position.top * controlyscale)), prefs.getInt(prefBase + "Right", (int) (template.position.right * controlxscale)), prefs.getInt(prefBase + "Bottom", (int) (template.position.bottom * controlyscale))); final BitmapFactory.Options controlOptions = new BitmapFactory.Options(); if (is565) controlOptions.inPreferredConfig = Bitmap.Config.RGB_565; final Bitmap originalControls = BitmapFactory.decodeResource(context.getResources(), resId, controlOptions); final Bitmap controls = Bitmap.createScaledBitmap(originalControls, finalRect.width(), finalRect.height(), true); return new Button(finalRect, id, controls); } else return new Button(template.position, id); }
/** * 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 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 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; }
@Override public Object instantiateItem(ViewGroup container, int position) { TouchImageView imgDisplay; Button btnClose; inflater = (LayoutInflater) _activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container, false); imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay); btnClose = (Button) viewLayout.findViewById(R.id.btnClose); BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options); imgDisplay.setImageBitmap(bitmap); // close button click event btnClose.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { _activity.finish(); } }); ((ViewPager) container).addView(viewLayout); return viewLayout; }
public static Bitmap fitSizeImg(String path) { if (path == null || path.length() < 1) return null; File file = new File(path); Bitmap resizeBmp = null; BitmapFactory.Options opts = new BitmapFactory.Options(); // 数字越大读出的图片占用的heap越小 不然总是溢出 if (file.length() < 51200) { // 0-50k opts.inSampleSize = 1; } else if (file.length() < 102400) { // 50-100k opts.inSampleSize = 2; } else if (file.length() < 204800) { // 100-200k opts.inSampleSize = 3; } else if (file.length() < 409600) { // 200-400k opts.inSampleSize = 4; } else if (file.length() < 614400) { // 400-600k opts.inSampleSize = 5; } else if (file.length() < 819200) { // 600-800k opts.inSampleSize = 6; } else if (file.length() < 1048576) { // 800-1m opts.inSampleSize = 7; } else if (file.length() < 2097152) { // 1m-2m opts.inSampleSize = 9; } else { opts.inSampleSize = 10; } opts.inPreferredConfig = Bitmap.Config.ARGB_8888; resizeBmp = BitmapFactory.decodeFile(file.getPath(), opts); return resizeBmp; }
/** * <根据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 static Bitmap LoadBackgroundBitmap(Context context, int id) throws Exception, OutOfMemoryError { Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int displayWidth = display.getWidth(); int displayHeight = display.getHeight(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Config.RGB_565; options.inJustDecodeBounds = true; float widthScale = options.outWidth / displayWidth; float heightScale = options.outHeight / displayHeight; float scale = widthScale > heightScale ? widthScale : heightScale; if (scale >= 8) options.inSampleSize = 8; else if (scale >= 6) options.inSampleSize = 6; else if (scale >= 4) options.inSampleSize = 4; else if (scale >= 2) options.inSampleSize = 2; else options.inSampleSize = 1; options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(context.getResources(), id, options); }
// 图片压缩 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); // 压缩好比例大小后再进行质量压缩 }
// if null so erreur public ArrayList<ArticleModel> getListModel(ArrayList<Article> listes, Context context) { ArrayList<ArticleModel> listeModel = new ArrayList<>(); try { for (int i = 0; i < listes.size(); i++) { File file = context.getFileStreamPath(listes.get(i).getIdArticle() + ".png"); if (file.exists()) { Bitmap bitmap = null; BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; try { bitmap = BitmapFactory.decodeStream(new FileInputStream(file), null, options); listeModel.add( new ArticleModel( bitmap, listes.get(i).getTitleArticle(), listes.get(i).getContentArticle())); } catch (FileNotFoundException e) { e.printStackTrace(); } } } return listeModel; } catch (Exception e) { e.printStackTrace(); } return null; }
public static Bitmap getImageFromByte(byte[] bytes, int sampleSize) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.RGB_565; options.inSampleSize = sampleSize; Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options); return Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight()); }
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 ""; }
public Bitmap loadImage(String path) throws OutOfMemoryError { Bitmap bitsat; try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.inJustDecodeBounds = true; Bitmap b = BitmapFactory.decodeFile(path, options); options.inSampleSize = Futils.calculateInSampleSize(options, px, px); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; Bitmap bit; if (path.startsWith("smb:/")) bit = BitmapFactory.decodeStream(new SmbFileInputStream(path)); else bit = BitmapFactory.decodeFile(path, options); bitsat = bit; // decodeFile(path);//.createScaledBitmap(bits,imageViewReference.get().getHeight(),imageViewReference.get().getWidth(),true); } catch (Exception e) { Drawable img = ContextCompat.getDrawable(mContext, R.drawable.ic_doc_image); Bitmap img1 = ((BitmapDrawable) img).getBitmap(); bitsat = img1; } return bitsat; }
public Cling(Context context) { this(context, null, 0); // bmp = Bitmap.createBitmap(Utils3D.getScreenWidth(), Utils3D.getScreenHeight(), // Bitmap.Config.ARGB_8888); // canvas = new Canvas(bmp); grad = new GradientDrawable( // 渐变色 Orientation.TOP_BOTTOM, new int[] {Color.BLACK, Color.WHITE}); options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.RGB_565; src1 = new Rect(); dst1 = new Rect(); src2 = new Rect(); dst2 = new Rect(); mErasePaint = new Paint(); mErasePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY)); // mErasePaint.setColor(0xFF18b7de); mErasePaint.setAlpha(0); mErasePaint.setAntiAlias(true); mErasePaint.setStyle(Paint.Style.FILL); mErasePaint.setStrokeWidth(4); normalPaint = new Paint(); normalPaint.setAntiAlias(true); normalPaint.setStyle(Paint.Style.STROKE); normalPaint.setStrokeWidth(strokeWidth); normalPaint.setColor(strokeColor); }
private boolean addTile() throws Exception { if (doesTileExist(client.getTileManager().getTiles().await(), tileId)) { return true; } /* Set the options */ BitmapFactory.Options options = new BitmapFactory.Options(); options.inScaled = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; Bitmap tileIcon = BitmapFactory.decodeResource( getBaseContext().getResources(), R.raw.drone_designer_icon, options); BandTile tile = new BandTile.Builder(tileId, "Drone", tileIcon) .setPageLayouts(createButtonLayout()) .build(); appendToUI("Button Tile is adding ...\n", 1); if (client.getTileManager().addTile(this, tile).await()) { appendToUI("Button Tile is added.\n", 1); return true; } else { appendToUI("Unable to add button tile to the band.\n", 1); return false; } }
public MediaStoreImage(Context context, String url) { mContext = context; mId = Long.parseLong(url.substring(PREFIX.length())); sBitmapOptionsCache.inPreferredConfig = Bitmap.Config.RGB_565; sBitmapOptionsCache.inDither = false; }
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; }
/** * 通过资源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); }
/** * 有两种办法将照片加载到bitmap中:2.用照片的真实路径加载 * * @param path 被加载的图像的路径 * @param width 加载后缩放到的目标宽度 * @param height 加载后缩放到的目标高度 * @return 加载并缩放后的位图 */ public static Bitmap loadBitmap(String path, int width, int height) { Bitmap mBitmap = null; BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; // FaceDetecor只能读取RGB 565格式的Bitmap Bitmap bitmap = BitmapFactory.decodeFile(path, options); mBitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height); // 缩放位图 return mBitmap; }
/** * Retrieve a dithered bitmap that can be used for comparison on any density * * @param resources * @param config the preferred config for the returning bitmap * @return the {@link Bitmap} or <code>null</code> */ public static Bitmap getUnscaledAndDitheredBitmap( Resources resources, int resId, Bitmap.Config config) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inDither = true; options.inScaled = false; options.inPreferredConfig = config; return BitmapFactory.decodeResource(resources, resId, options); }
/** * * 根据资源文件获取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 decodeBitmap(InputStream is) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inDither = true; // Prefer the bitmap config we computed from the window parameter options.inPreferredConfig = graphics.preferredBitmapConfig; // Never scale bitmaps based on device parameters options.inScaled = false; return BitmapFactory.decodeStream(is, null, options); }
@Test public void decodeResource_shouldPassABitmapConfig() throws Exception { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ALPHA_8; Bitmap bitmap = BitmapFactory.decodeResource( Robolectric.application.getResources(), R.drawable.an_image, options); assertThat(bitmap.getConfig()).isEqualTo(Bitmap.Config.ALPHA_8); }
// decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f, String size) { try { // decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; FileInputStream stream1 = new FileInputStream(f); BitmapFactory.decodeStream(stream1, null, o); stream1.close(); int REQUIRED_SIZE = 200; // Find the correct scale value. It should be the power of 2. if (size.equals(SMALL)) { REQUIRED_SIZE = SIZE_SMALL; } else if (size.equals(LARGE)) { REQUIRED_SIZE = SIZE_LARGE; } int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // scale=4; // decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; if (Utils.isOsVersionHigherThenGingerbread()) { o2.inPreferredConfig = Bitmap.Config.ARGB_8888; } else { o2.inPreferredConfig = Bitmap.Config.RGB_565; } FileInputStream stream2 = new FileInputStream(f); Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2); stream2.close(); return bitmap; } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } return null; }