Java Code Examples for android.graphics.Bitmap.Config#ARGB_8888

The following examples show how to use android.graphics.Bitmap.Config#ARGB_8888 . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NativeUtil.java    From faceswap with Apache License 2.0 6 votes vote down vote up
public static void compressBitmap(Bitmap bit, int quality, String fileName,
                                  boolean optimize) {
    Log.d("native", "compress of native");
    if (bit.getConfig() != Config.ARGB_8888) {
        Bitmap result = null;

        result = Bitmap.createBitmap(bit.getWidth(), bit.getHeight(),
                Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Rect rect = new Rect(0, 0, bit.getWidth(), bit.getHeight());
        canvas.drawBitmap(bit, null, rect, null);
        saveBitmap(result, quality, fileName, optimize);
        result.recycle();
    } else {
        saveBitmap(bit, quality, fileName, optimize);
    }

}
 
Example 2
Source File: PLUtils.java    From panoramagl with Apache License 2.0 6 votes vote down vote up
/**
 * conversion methods
 */

public static Config convertTextureColorFormatToBitmapConfig(PLTextureColorFormat colorFormat) {
    Config config = Config.ARGB_8888;
    switch (colorFormat) {
        case PLTextureColorFormatRGB565:
            config = Config.RGB_565;
            break;
        case PLTextureColorFormatRGBA4444:
            config = Config.ARGB_4444;
            break;
        default:
            break;
    }
    return config;
}
 
Example 3
Source File: SignupPage.java    From ThirdPartyLoginDemo with MIT License 5 votes vote down vote up
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;
	}
 
Example 4
Source File: ImageCache.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the byte usage per pixel of a bitmap based on its configuration.
 * 
 * @param config
 *            The bitmap configuration.
 * @return The byte usage per pixel.
 */
private static int getBytesPerPixel(Config config) {
	if (config == Config.ARGB_8888) {
		return 4;
	} else if (config == Config.RGB_565) {
		return 2;
	} else if (config == Config.ARGB_4444) {
		return 2;
	} else if (config == Config.ALPHA_8) {
		return 1;
	}
	return 1;
}
 
Example 5
Source File: DrawableBitmapResourceDecoder.java    From glide-support with The Unlicense 5 votes vote down vote up
@Override public Resource<Bitmap> decode(Drawable drawable, int width, int height) throws IOException {
	Config config = PixelFormat.formatHasAlpha(drawable.getOpacity())? Config.ARGB_8888 : Config.RGB_565;
	Bitmap bitmap = pool.get(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), config);
	if (bitmap == null) {
		bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), config);
	}
	Canvas canvas = new Canvas(bitmap);
	drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
	drawable.draw(canvas);
	return new BitmapResource(bitmap, pool);
}
 
Example 6
Source File: CompressImageUtil.java    From TakePhoto with Apache License 2.0 5 votes vote down vote up
/**
 * 按比例缩小图片的像素以达到压缩的目的
 *
 * @param imgPath
 * @return
 * @author JPH
 * @date 2014-12-5下午11:30:59
 */
private void compressImageByPixel(String imgPath, CompressListener listener) throws FileNotFoundException {
    if (imgPath == null) {
        sendMsg(false, imgPath, "要压缩的文件不存在", listener);
        return;
    }
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    newOpts.inJustDecodeBounds = true;//只读边,不读内容
    BitmapFactory.decodeFile(imgPath, newOpts);
    newOpts.inJustDecodeBounds = false;
    int width = newOpts.outWidth;
    int height = newOpts.outHeight;
    float maxSize = config.getMaxPixel();
    int be = 1;
    if (width >= height && width > maxSize) {//缩放比,用高或者宽其中较大的一个数据进行计算
        be = (int) (newOpts.outWidth / maxSize);
        be++;
    } else if (width < height && height > maxSize) {
        be = (int) (newOpts.outHeight / maxSize);
        be++;
    }
    newOpts.inSampleSize = be;//设置采样率
    newOpts.inPreferredConfig = Config.ARGB_8888;//该模式是默认的,可不设
    newOpts.inPurgeable = true;// 同时设置才会有效
    newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收
    Bitmap bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
    if (config.isEnableQualityCompress()) {
        compressImageByQuality(bitmap, imgPath, listener);//压缩好比例大小后再进行质量压缩
    } else {
        File thumbnailFile = getThumbnailFile(new File(imgPath));
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(thumbnailFile));

        listener.onCompressSuccess(thumbnailFile.getPath());
    }
}
 
Example 7
Source File: MenusAdapter.java    From elemeimitate with Apache License 2.0 5 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
	final ViewHolder viewHolder ;
	if(convertView == null){
		convertView = inflater.inflate(R.layout.item_menu_content, parent, false);
		viewHolder = new ViewHolder();
		viewHolder.iv_image = (ImageView)convertView.findViewById(R.id.item_menu_content_img);
		viewHolder.tv_menusName = (TextView)convertView.findViewById(R.id.item_menu_content_title);
		viewHolder.tv_price = (TextView)convertView.findViewById(R.id.item_menu_content_price);
		
		convertView.setTag(viewHolder);
	}else{
		viewHolder = (ViewHolder)convertView.getTag();
	}

	//创建一个RequestQueue对象
	RequestQueue requestQueue = Volley.newRequestQueue(context);
	     	
    //创建ImageRequest对象
	ImageRequest imageRequest = new ImageRequest(
			Constant.URL_WEB_SERVER+datas.get(position).get("menusImagePath").toString(),//url
	    	new Response.Listener<Bitmap>() {//监听器Listener
				@Override
	    		public void onResponse(Bitmap response) {
	    			viewHolder.iv_image.setImageBitmap(response);
	    		}
	    		//参数3、4表示图片宽高,Bitmap.Config.ARGB_8888表示图片每个像素占据4个字节大小
	    	}, 0, 0, Config.ARGB_8888, new Response.ErrorListener() {//图片加载请求失败的回调Listener
	    			@Override
	    			public void onErrorResponse(VolleyError error) {
	    				viewHolder.iv_image.setImageResource(R.drawable.ic_normal_pic);
	    			}
	    	});
	//将ImageRequest加载到Queue
	 requestQueue.add(imageRequest);
	    
	viewHolder.tv_menusName.setText(datas.get(position).get("menuName").toString());
	viewHolder.tv_price.setText("¥"+datas.get(position).get("total_price").toString());
	return convertView;
}
 
Example 8
Source File: BitmapUtil.java    From a with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 通过资源id转化成Bitmap
 */
public static Bitmap ReadBitmapById(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);
}
 
Example 9
Source File: LogoView.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Starts playing the given animated GIF logo.
 */
public void playAnimatedLogo(BaseGifImage gifImage) {
    mLoadingView.hideLoadingUI();
    mAnimatedLogoDrawable = new BaseGifDrawable(gifImage, Config.ARGB_8888);
    mAnimatedLogoMatrix = new Matrix();
    setMatrix(mAnimatedLogoDrawable.getIntrinsicWidth(),
            mAnimatedLogoDrawable.getIntrinsicHeight(), mAnimatedLogoMatrix, false);
    // Set callback here to ensure #invalidateDrawable() is called.
    mAnimatedLogoDrawable.setCallback(this);
    mAnimatedLogoDrawable.start();
}
 
Example 10
Source File: ImageProvider.java    From cube-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Return the byte usage per pixel of a bitmap based on its configuration.
 *
 * @param config The bitmap configuration.
 * @return The byte usage per pixel.
 */
private static int getBytesPerPixel(Config config) {
    if (config == Config.ARGB_8888) {
        return 4;
    } else if (config == Config.RGB_565) {
        return 2;
    } else if (config == Config.ARGB_4444) {
        return 2;
    } else if (config == Config.ALPHA_8) {
        return 1;
    }
    return 1;
}
 
Example 11
Source File: BitmapUtil.java    From lunzi with Apache License 2.0 5 votes vote down vote up
/**
 * @param resources 传入Resources
 * @param resid     资源ID
 * @param size      要压缩的大小
 * @return
 */
public static Bitmap getSmallBitmap(Resources resources, int resid, int size) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(resources, resid, options);

    // Calculate inSampleSize
    options.inSampleSize = size;
    Log.i("Bitmap", "--" + options.inSampleSize);
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    options.inPreferredConfig = Config.ARGB_8888;
    Bitmap bitmap = BitmapFactory.decodeResource(resources, resid, options);
    if (bitmap == null) {
        return null;
    }
    ByteArrayOutputStream baos = null;
    try {
        baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    } finally {
        try {
            if (baos != null) baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return bitmap;
}
 
Example 12
Source File: Cache.java    From tns-core-modules-widgets with Apache License 2.0 5 votes vote down vote up
/**
 * Return the byte usage per pixel of a bitmap based on its configuration.
 *
 * @param config The bitmap configuration.
 * @return The byte usage per pixel.
 */
private static int getBytesPerPixel(Config config) {
    if (config == Config.ARGB_8888) {
        return 4;
    } else if (config == Config.RGB_565) {
        return 2;
    } else if (config == Config.ARGB_4444) {
        return 2;
    } else if (config == Config.ALPHA_8) {
        return 1;
    }
    return 1;
}
 
Example 13
Source File: ImageCache.java    From vocefiscal-android with Apache License 2.0 5 votes vote down vote up
/**
 * Return the byte usage per pixel of a bitmap based on its configuration.
 * @param config The bitmap configuration.
 * @return The byte usage per pixel.
 */
private static int getBytesPerPixel(Config config) {
    if (config == Config.ARGB_8888) {
        return 4;
    } else if (config == Config.RGB_565) {
        return 2;
    } else if (config == Config.ARGB_4444) {
        return 2;
    } else if (config == Config.ALPHA_8) {
        return 1;
    }
    return 1;
}
 
Example 14
Source File: FileUtils.java    From NoVIP with Apache License 2.0 5 votes vote down vote up
/**
 *  将图片从本地读到内存时,进行压缩 ,即图片从File形式变为Bitmap形式
 *  特点: 通过设置采样率, 减少图片的像素, 达到对内存中的Bitmap进行压缩
 * @param srcPath
 * @return
 */
public static Bitmap compressImageFromFile(String srcPath, float pixWidth, float pixHeight) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;// 只读边,不读内容
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, options);

    options.inJustDecodeBounds = false;
    int w = options.outWidth;
    int h = options.outHeight;
    //float pixWidth = 800f;//
    //float pixHeight = 480f;//
    int scale = 1;
    if (w > h && w > pixWidth) {
        scale = (int) (options.outWidth / pixWidth);
    } else if (w < h && h > pixHeight) {
        scale = (int) (options.outHeight / pixHeight);
    }
    if (scale <= 0)
        scale = 1;
    options.inSampleSize = scale;// 设置采样率

    options.inPreferredConfig = Config.ARGB_8888;// 该模式是默认的,可不设
    options.inPurgeable = true;// 同时设置才会有效
    options.inInputShareable = true;// 。当系统内存不够时候图片自动被回收

    bitmap = BitmapFactory.decodeFile(srcPath, options);
    // return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
    // 其实是无效的,大家尽管尝试
    return bitmap;
}
 
Example 15
Source File: ImageCache.java    From BubbleCloudView with MIT License 5 votes vote down vote up
/**
 * Return the byte usage per pixel of a bitmap based on its configuration.
 * @param config The bitmap configuration.
 * @return The byte usage per pixel.
 */
private static int getBytesPerPixel(Config config) {
    if (config == Config.ARGB_8888) {
        return 4;
    } else if (config == Config.RGB_565) {
        return 2;
    } else if (config == Config.ARGB_4444) {
        return 2;
    } else if (config == Config.ALPHA_8) {
        return 1;
    }
    return 1;
}
 
Example 16
Source File: BitmapUtil.java    From lunzi with Apache License 2.0 5 votes vote down vote up
/**
 * @param resources 传入Resources
 * @param resid     资源ID
 * @param width     目标width
 * @param height    目标height
 * @return
 */
public static Bitmap getSmallBitmap(Resources resources, int resid, int width, int height) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(resources, resid, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, width, height);
    Log.i("Bitmap", "--" + options.inSampleSize);
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    options.inPreferredConfig = Config.ARGB_8888;
    Bitmap bitmap = BitmapFactory.decodeResource(resources, resid, options);
    if (bitmap == null) {
        return null;
    }
    ByteArrayOutputStream baos = null;
    try {
        baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    } finally {
        try {
            if (baos != null) baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return bitmap;
}
 
Example 17
Source File: OrderAdapter.java    From elemeimitate with Apache License 2.0 4 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
	final ViewHolder viewHolder ;
	if(convertView == null){
		convertView = inflater.inflate(R.layout.item_list_order, parent, false);
		viewHolder = new ViewHolder();
		viewHolder.iv_image = (ImageView)convertView.findViewById(R.id.order_iv);
		viewHolder.tv_menusName = (TextView)convertView.findViewById(R.id.order_menusName_tv);
		viewHolder.tv_amount = (TextView)convertView.findViewById(R.id.order_amount_tv);
		viewHolder.tv_time = (TextView)convertView.findViewById(R.id.order_time_tv);
		viewHolder.tv_price = (TextView)convertView.findViewById(R.id.order_price_tv);
		viewHolder.tv_status = (TextView)convertView.findViewById(R.id.order_status_tv);
		
		convertView.setTag(viewHolder);
	}else{
		viewHolder = (ViewHolder)convertView.getTag();
	}

	//创建一个RequestQueue对象
	RequestQueue requestQueue = Volley.newRequestQueue(context);
	     	
    //创建ImageRequest对象
	ImageRequest imageRequest = new ImageRequest(
			Constant.URL_WEB_SERVER+datas.get(position).get("picPath").toString(),//url
	    	new Response.Listener<Bitmap>() {//监听器Listener
				@Override
	    		public void onResponse(Bitmap response) {
	    			viewHolder.iv_image.setImageBitmap(response);
	    		}
	    		//参数3、4表示图片宽高,Bitmap.Config.ARGB_8888表示图片每个像素占据4个字节大小
	    	}, 0, 0, Config.ARGB_8888, new Response.ErrorListener() {//图片加载请求失败的回调Listener
	    			@Override
	    			public void onErrorResponse(VolleyError error) {
	    				viewHolder.iv_image.setImageResource(R.drawable.ic_normal_pic);
	    			}
	    	});
	//将ImageRequest加载到Queue
	 requestQueue.add(imageRequest);
	    
	viewHolder.tv_menusName.setText(datas.get(position).get("name").toString());
	viewHolder.tv_amount.setText("×"+datas.get(position).get("amount").toString());
	viewHolder.tv_time.setText("订单时间:"+datas.get(position).get("order_time").toString());
	viewHolder.tv_price.setText("总价:¥"+datas.get(position).get("total_price").toString());
	viewHolder.tv_status.setText(datas.get(position).get("status").toString());
	return convertView;
}
 
Example 18
Source File: BitmapTextureAtlas.java    From 30-android-libraries-in-30-days with Apache License 2.0 4 votes vote down vote up
@Override
protected void writeTextureToHardware(final GLState pGLState) {
	final PixelFormat pixelFormat = this.mBitmapTextureFormat.getPixelFormat();
	final int glInternalFormat = pixelFormat.getGLInternalFormat();
	final int glFormat = pixelFormat.getGLFormat();
	final int glType = pixelFormat.getGLType();

	GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, glInternalFormat, this.mWidth, this.mHeight, 0, glFormat, glType, null);

	final boolean preMultipyAlpha = this.mTextureOptions.mPreMultiplyAlpha;
	/* Non alpha premultiplied bitmaps are loaded with ARGB_8888 and converted down manually. */
	final Config bitmapConfig = (preMultipyAlpha) ? this.mBitmapTextureFormat.getBitmapConfig() : Config.ARGB_8888;

	final ArrayList<IBitmapTextureAtlasSource> textureSources = this.mTextureAtlasSources;
	final int textureSourceCount = textureSources.size();

	final ITextureAtlasStateListener<IBitmapTextureAtlasSource> textureStateListener = this.getTextureAtlasStateListener();
	for(int i = 0; i < textureSourceCount; i++) {
		final IBitmapTextureAtlasSource bitmapTextureAtlasSource = textureSources.get(i);
		try {
			final Bitmap bitmap = bitmapTextureAtlasSource.onLoadBitmap(bitmapConfig);
			if(bitmap == null) {
				throw new NullBitmapException("Caused by: " + bitmapTextureAtlasSource.getClass().toString() + " --> " + bitmapTextureAtlasSource.toString() + " returned a null Bitmap.");
			}

			final boolean useDefaultAlignment = MathUtils.isPowerOfTwo(bitmap.getWidth()) && MathUtils.isPowerOfTwo(bitmap.getHeight()) && pixelFormat == PixelFormat.RGBA_8888;
			if(!useDefaultAlignment) {
				/* Adjust unpack alignment. */
				GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1);
			}

			if(preMultipyAlpha) {
				GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, bitmapTextureAtlasSource.getTextureX(), bitmapTextureAtlasSource.getTextureY(), bitmap, glFormat, glType);
			} else {
				pGLState.glTexSubImage2D(GLES20.GL_TEXTURE_2D, 0, bitmapTextureAtlasSource.getTextureX(), bitmapTextureAtlasSource.getTextureY(), bitmap, this.mPixelFormat);
			}

			if(!useDefaultAlignment) {
				/* Restore default unpack alignment. */
				GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, GLState.GL_UNPACK_ALIGNMENT_DEFAULT);
			}

			bitmap.recycle();

			if(textureStateListener != null) {
				textureStateListener.onTextureAtlasSourceLoaded(this, bitmapTextureAtlasSource);
			}
		} catch (final NullBitmapException e) {
			if(textureStateListener != null) {
				textureStateListener.onTextureAtlasSourceLoadExeption(this, bitmapTextureAtlasSource, e);
			} else {
				throw e;
			}
		}
	}
}
 
Example 19
Source File: EditBitmapUtils.java    From iBeebo with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Decodes bitmap that keeps aspect-ratio and spans most within the bounds.
 */
private Bitmap decodeBitmap(Uri uri, int width, int height) {
    InputStream is = null;
    Bitmap bitmap = null;

    try {
        // TODO: Take max pixels allowed into account for calculation to avoid possible OOM.
        Rect bounds = getBitmapBounds(uri);
        int sampleSize = Math.max(bounds.width() / width, bounds.height() / height);
        sampleSize = Math.min(sampleSize, Math.max(bounds.width() / height, bounds.height() / width));

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = Math.max(sampleSize, 1);
        options.inPreferredConfig = Config.ARGB_8888;

        is = context.getContentResolver().openInputStream(uri);
        bitmap = BitmapFactory.decodeStream(is, null, options);
    } catch (FileNotFoundException e) {
        Log.e(TAG, "FileNotFoundException: " + uri);
    } finally {
        closeStream(is);
    }

    // Ensure bitmap in 8888 format, good for editing as well as GL compatible.
    if ((bitmap != null) && (bitmap.getConfig() != Config.ARGB_8888)) {
        Bitmap copy = bitmap.copy(Config.ARGB_8888, true);
        bitmap.recycle();
        bitmap = copy;
    }

    if (bitmap != null) {
        // Scale down the sampled bitmap if it's still larger than the desired dimension.
        float scale = Math.min((float) width / bitmap.getWidth(), (float) height / bitmap.getHeight());
        scale = Math.max(scale, Math.min((float) height / bitmap.getWidth(), (float) width / bitmap.getHeight()));
        if (scale < 1) {
            Matrix m = new Matrix();
            m.setScale(scale, scale);
            Bitmap transformed = createBitmap(bitmap, m);
            bitmap.recycle();
            return transformed;
        }
    }
    return bitmap;
}
 
Example 20
Source File: EditBitmapUtils.java    From iBeebo with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Decodes bitmap that keeps aspect-ratio and spans most within the bounds.
 */
private Bitmap decodeBitmap(Uri uri, int width, int height) {
    InputStream is = null;
    Bitmap bitmap = null;

    try {
        // TODO: Take max pixels allowed into account for calculation to avoid possible OOM.
        Rect bounds = getBitmapBounds(uri);
        int sampleSize = Math.max(bounds.width() / width, bounds.height() / height);
        sampleSize = Math.min(sampleSize, Math.max(bounds.width() / height, bounds.height() / width));

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = Math.max(sampleSize, 1);
        options.inPreferredConfig = Config.ARGB_8888;

        is = context.getContentResolver().openInputStream(uri);
        bitmap = BitmapFactory.decodeStream(is, null, options);
    } catch (FileNotFoundException e) {
        Log.e(TAG, "FileNotFoundException: " + uri);
    } finally {
        closeStream(is);
    }

    // Ensure bitmap in 8888 format, good for editing as well as GL compatible.
    if ((bitmap != null) && (bitmap.getConfig() != Config.ARGB_8888)) {
        Bitmap copy = bitmap.copy(Config.ARGB_8888, true);
        bitmap.recycle();
        bitmap = copy;
    }

    if (bitmap != null) {
        // Scale down the sampled bitmap if it's still larger than the desired dimension.
        float scale = Math.min((float) width / bitmap.getWidth(), (float) height / bitmap.getHeight());
        scale = Math.max(scale, Math.min((float) height / bitmap.getWidth(), (float) width / bitmap.getHeight()));
        if (scale < 1) {
            Matrix m = new Matrix();
            m.setScale(scale, scale);
            Bitmap transformed = createBitmap(bitmap, m);
            bitmap.recycle();
            return transformed;
        }
    }
    return bitmap;
}