it is troublesome to translate among them.
Bitmap is a very convenient representation of an image,
here are some rules between bitmap and other representations:
1. Bitmap from resource
- Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
- R.drawable.resource);
2. Bitmap from/to a image file in the sd card
- BitmapFactory.Options option = new BitmapFactory.Options();
- option.inSampleSize = 2;
- Bitmap bitmap = BitmapFactory.decodeFile("sdcard/image.jpg", option);
option.inSampleSize = 2 implies the resolution of image file is divided by 2
- if (bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos)){
- fos.flush();
- fos.close();
- }
This translation requires the permission :<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
3. Bitmap from View or the View-liked components
- myView.setDrawingCacheEnabled(true);
- myView.destroyDrawingCache();
- Bitmap bitmap = myView.getDrawingCache();
We can fetch the content of a view (include ImageView, WebView ...) by enable the drawing cache of it. Once the getDrawingCache is called, the bitmap will be generated according to the previous canvas the view contains. If we want to fetch the latest content, it is necessary to destroy the drawing cache first (If the drawing cache is null, getDrawingCache() will generate the current status).
4. Bitmap from/to drawable
- BitmapDrawable bitmapDrawable = (BitmapDrawable)drawable;
- Bitmap bitmap = bitmapDrawable.getBitmap();
- Drawable drawable = new BitmapDrawable(bitmap);
The above code is not verified, maybe you can try it.
5. Bitmap from/to canvas
- Bitmap bitmap = Bitmap.createBitmap(canvas.getWidth(),
- canvas.getHeight(), Bitmap.Config.ARGB_4444);
The above code let us "draw" some figures to the bitmap instead of "get" the figures which are draw at the canvas. If you want to achieve the latter functionality, just try the rule 3.
- canvas.drawBitmap(bitmap, left, top, paint);
The canvas.drawBitmap can display any bitmap to a certain location of your canvas.
No comments:
Post a Comment