Android examples for android.graphics:Bitmap Load Save
Reads bitmap from bytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; public class Main { /**/*from w w w .jav a 2 s . co m*/ * Reads bitmap from bytes * * @param bytes * @return */ public static Bitmap readBitmap(byte[] data) { if (data != null) { Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length); return bmp; } return null; } /** * Reads bitmap from byte[] and returns bitmap in requested size * * @param data * @param width * - of requested bitmap * @param height * - of requested bitmap * @return */ public static Bitmap readBitmap(byte[] data, int width, int height) { Bitmap tempBmp = null; Options options = null; try { InputStream is = new ByteArrayInputStream(data); options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inPreferredConfig = Config.ARGB_8888; options.inSampleSize = 5; tempBmp = BitmapFactory.decodeStream(is, null, options); options.inSampleSize = calculateInSampleSize(options, width, height); options.inJustDecodeBounds = false; options.inBitmap = tempBmp; is.close(); } catch (IOException e) { e.printStackTrace(); } try { InputStream is = new ByteArrayInputStream(data); tempBmp = BitmapFactory.decodeStream(is, null, options); is.close(); } catch (IOException e) { e.printStackTrace(); } return tempBmp; } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; } }