public DessertCaseView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); final Resources res = getResources(); mStarted = false; mCellSize = res.getDimensionPixelSize(R.dimen.dessert_case_cell_size); final BitmapFactory.Options opts = new BitmapFactory.Options(); if (mCellSize < 512) { // assuming 512x512 images opts.inSampleSize = 2; } opts.inMutable = true; Bitmap loaded = null; for (int[] list : new int[][] {PASTRIES, RARE_PASTRIES, XRARE_PASTRIES, XXRARE_PASTRIES}) { for (int resid : list) { opts.inBitmap = loaded; loaded = BitmapFactory.decodeResource(res, resid, opts); final BitmapDrawable d = new BitmapDrawable(res, convertToAlphaMask(loaded)); d.setColorFilter(new ColorMatrixColorFilter(ALPHA_MASK)); d.setBounds(0, 0, mCellSize, mCellSize); mDrawables.append(resid, d); } } loaded = null; if (DEBUG) setWillNotDraw(false); }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inMutable = true; Bitmap bmp = BitmapFactory.decodeFile(picturePath, options); int y = bmp.getHeight() / 2; int x = bmp.getWidth() / 2; Canvas canvas = new Canvas(bmp); Paint myPaint = new Paint(); myPaint.setColor(Color.YELLOW); myPaint.setTextSize(25); canvas.drawText("Sample Text", x, y, myPaint); ImageView imageView = (ImageView) findViewById(R.id.imgView); imageView.setImageBitmap(bmp); } }
/** * ponerOpcionInBitmap: Checa si es posible reutilizar un bitmap desechado de acuerdo a los * requerimientos de esta imagen en particular, de ser asi activa la opcion inBitmap. * * @param opciones BitmapFactory.Options de la imagen nueva. */ private void ponerOpcionInBitmap(BitmapFactory.Options opciones) { // Tiene que ser mutable opciones.inMutable = true; Bitmap bitmap_reutilizable = obtenerBitmapDesechado(opciones); // Activa inBitmap en las opciones con el bitmap encontrado if (bitmap_reutilizable != null) { opciones.inBitmap = bitmap_reutilizable; } }
@TargetApi(Build.VERSION_CODES.HONEYCOMB) private void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) { options.inMutable = true; if (cache != null) { Bitmap inBitmap = cache.getBitmapFromReusableSet(options); if (inBitmap != null) { options.inBitmap = inBitmap; } } }
/** * Decode and sample down a bitmap from a file to the requested width and height. * * @param filePath The full path of the file to decode * @param reqWidth The requested width of the resulting bitmap * @param reqHeight The requested height of the resulting bitmap * @param isMutable 可编辑 * @return A bitmap sampled down from the original with the same aspect ratio and dimensions that * are equal to or greater than the requested width and height */ public static Bitmap decodeSampledBitmapFromFile( String filePath, int reqWidth, int reqHeight, boolean isMutable, boolean regionDecode) { if (filePath == null) { return null; } if (reqHeight == 0) { reqHeight = MAX_TEXTURE_SIZE; } if (reqWidth == 0) { reqWidth = MAX_TEXTURE_SIZE; } // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); if (options.outWidth == -1 || options.outHeight == -1) { return null; } // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); if (isMutable && Build.VERSION.SDK_INT >= 11) { options.inMutable = true; } Bitmap result = null; if ((options.outWidth > MAX_TEXTURE_SIZE || options.outHeight > MAX_TEXTURE_SIZE || (options.outHeight >= options.outWidth * 3)) && regionDecode) { // 长图 try { result = regionDecode(filePath, reqWidth, reqHeight, options.outWidth, options.outHeight); } catch (IOException e) { e.printStackTrace(); } } else { result = BitmapFactory.decodeFile(filePath, options); } if (isMutable) { result = createMutableBitmap(result); } return result; }
private static void addInBitmapOptions( BitmapFactory.Options options, Set<SoftReference<Bitmap>> reuseableBitmaps) { // inBitmap only works with mutable bitmaps, so force the decoder to // return mutable bitmaps. options.inMutable = true; // Try to find a bitmap to use for inBitmap. Bitmap inBitmap = getBitmapFromReusableSet(reuseableBitmaps, options); if (inBitmap != null) { // If a suitable bitmap has been found, set it as the value of // inBitmap. options.inBitmap = inBitmap; } }
@TargetApi(Build.VERSION_CODES.HONEYCOMB) private static void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) { // BEGIN_INCLUDE(add_bitmap_options) // inBitmap only works with mutable bitmaps so force the decoder to // return mutable bitmaps. options.inMutable = true; if (cache != null) { // Try and find a bitmap to use for inBitmap Bitmap inBitmap = cache.getBitmapFromReusableSet(options); if (inBitmap != null) { options.inBitmap = inBitmap; } } // END_INCLUDE(add_bitmap_options) }
public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inMutable = true; options.inBitmap = BitmapFactory.decodeFile(path, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inScaled = true; options.inDensity = options.outWidth; options.inTargetDensity = reqWidth * options.inSampleSize; options.inJustDecodeBounds = false; options.inPurgeable = true; options.inInputShareable = true; return BitmapFactory.decodeFile(path, options); }
/** * Options returned by this method are configured with mDecodeBuffer which is GuardedBy("this") */ private static BitmapFactory.Options getDecodeOptionsForStream( EncodedImage encodedImage, Bitmap.Config bitmapConfig) { final BitmapFactory.Options options = new BitmapFactory.Options(); // Sample size should ONLY be different than 1 when downsampling is enabled in the pipeline options.inSampleSize = encodedImage.getSampleSize(); options.inJustDecodeBounds = true; // fill outWidth and outHeight BitmapFactory.decodeStream(encodedImage.getInputStream(), null, options); if (options.outWidth == -1 || options.outHeight == -1) { throw new IllegalArgumentException(); } options.inJustDecodeBounds = false; options.inDither = true; options.inPreferredConfig = bitmapConfig; options.inMutable = true; return options; }
/** Decode and sample down a bitmap from a byte stream */ public static Bitmap decodeSampledBitmapFromByte(Context context, byte[] bitmapBytes) { Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int reqWidth, reqHeight; Point point = new Point(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { display.getSize(point); reqWidth = point.x; reqHeight = point.y; } else { reqWidth = display.getWidth(); reqHeight = display.getHeight(); } final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inMutable = true; options.inBitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Load & resize the image to be 1/inSampleSize dimensions // Use when you do not want to scale the image with a inSampleSize that is a power of 2 options.inScaled = true; options.inDensity = options.outWidth; options.inTargetDensity = reqWidth * options.inSampleSize; // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; // If set to true, the decoder will return null (no bitmap), but the out... fields // will still be set, allowing the caller to query the bitmap without having to // allocate the memory for its pixels. options.inPurgeable = true; // Tell to gc that whether it needs free memory, the Bitmap can be cleared options.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 return BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length, options); }
/* Convertimos los bytes a un JPEG */ public static synchronized Bitmap setBitmapFromYUV( byte[] data, Rect imRoi, int previewWidth, int previewHeight) { /** * ****************************************************************************************** * Esta función toma un arreglo de bytes directo de la camara en formato NV21 (YUV) y lo * transforma en un bitmap en formato rgba en formato jpeg. * ******************************************************************************************* */ BitmapFactory.Options imBmpFactoryOptions = new BitmapFactory.Options(); // Opciones del bitmapFactory imBmpFactoryOptions.inPreferredConfig = Bitmap.Config.RGB_565; // Formato. imBmpFactoryOptions.inMutable = true; // Podemos modificarlo YuvImage imYUV = new YuvImage( data, ImageFormat.NV21, previewWidth, previewHeight, null); // Obtenemos una imagen YUV ByteArrayOutputStream imBAOS = new ByteArrayOutputStream(); // Generamos un BAOS. imYUV.compressToJpeg( imRoi, 100, imBAOS); // Obtenemos la compresión de la imagen YUV a JPEG en el BAOS. byte[] imJPEGData = imBAOS.toByteArray(); // Obtenemos un array de la imagen a partir del BAOs. return BitmapFactory.decodeByteArray( imJPEGData, 0, imJPEGData.length, imBmpFactoryOptions); // Generamos el Bitmap. }
@TargetApi(11) private BitmapFactory.Options createTileBitmapFactoryOptions( int tileSize, boolean isTransparent) { BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options(); if (isTransparent) { bitmapFactoryOptions.inPreferredConfig = AndroidGraphicFactory.TRANSPARENT_BITMAP; } else { bitmapFactoryOptions.inPreferredConfig = AndroidGraphicFactory.NON_TRANSPARENT_BITMAP; } if (org.mapsforge.map.android.util.AndroidUtil.HONEYCOMB_PLUS) { android.graphics.Bitmap reusableBitmap = getTileBitmapFromReusableSet(tileSize, isTransparent); if (reusableBitmap != null) { bitmapFactoryOptions.inMutable = true; bitmapFactoryOptions.inSampleSize = 1; // not really sure why this is required, but otherwise decoding // fails bitmapFactoryOptions.inBitmap = getTileBitmapFromReusableSet(tileSize, isTransparent); } } return bitmapFactoryOptions; }
/** * Decode and sample down a bitmap from resources to the requested width and height. * * @param res The resources object containing the image data * @param resId The resource id of the image data * @param reqWidth The requested width of the resulting bitmap * @param reqHeight The requested height of the resulting bitmap * @param isMutable 可编辑 * @return A bitmap sampled down from the original with the same aspect ratio and dimensions that * are equal to or greater than the requested width and height */ public static Bitmap decodeSampledBitmapFromResource( Resources res, int resId, int reqWidth, int reqHeight, boolean isMutable) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; if (isMutable && Build.VERSION.SDK_INT >= 11) { options.inMutable = true; } Bitmap result = BitmapFactory.decodeResource(res, resId, options); if (isMutable) { result = createMutableBitmap(result); } return result; }
public static Bitmap decodeSampledBitmapFromByteArray( byte[] data, int reqWidth, int reqHeight, HashSet<SoftReference<Bitmap>> reusableBitmapSet) { if (data == null) { return null; } if (reqHeight == 0) { reqHeight = MAX_TEXTURE_SIZE; } if (reqWidth == 0) { reqWidth = MAX_TEXTURE_SIZE; } // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, options); if (options.outWidth == -1 || options.outHeight == -1) { return null; } // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); if (Build.VERSION.SDK_INT >= 11) { options.inMutable = true; if (reusableBitmapSet != null) { addInBitmapOptions(options, reusableBitmapSet); } } return BitmapFactory.decodeByteArray(data, 0, data.length, options); }
public Bitmap getRawBitmap(byte[] data) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inMutable = true; options.inBitmap = raw; return BitmapFactory.decodeByteArray(data, 0, data.length, options); }
@TargetApi(Build.VERSION_CODES.HONEYCOMB) public static Bitmap extractThumbNail( final String path, final int width, final int height, final boolean crop) { Assert.assertTrue(path != null && !path.equals("") && height > 0 && width > 0); BitmapFactory.Options options = new BitmapFactory.Options(); try { options.inJustDecodeBounds = true; Bitmap tmp = BitmapFactory.decodeFile(path, options); if (tmp != null) { tmp.recycle(); tmp = null; } LogUtil.d(TAG, "extractThumbNail: round=" + width + "x" + height + ", crop=" + crop); final double beY = options.outHeight * 1.0 / height; final double beX = options.outWidth * 1.0 / width; LogUtil.d(TAG, "extractThumbNail: extract beX = " + beX + ", beY = " + beY); options.inSampleSize = (int) (crop ? (beY > beX ? beX : beY) : (beY < beX ? beX : beY)); if (options.inSampleSize <= 1) { options.inSampleSize = 1; } // NOTE: out of memory error while (options.outHeight * options.outWidth / options.inSampleSize > MAX_DECODE_PICTURE_SIZE) { options.inSampleSize++; } int newHeight = height; int newWidth = width; if (crop) { if (beY > beX) { newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth); } else { newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight); } } else { if (beY < beX) { newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth); } else { newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight); } } options.inJustDecodeBounds = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { options.inMutable = true; } LogUtil.i( TAG, "bitmap required size=" + newWidth + "x" + newHeight + ", orig=" + options.outWidth + "x" + options.outHeight + ", sample=" + options.inSampleSize); Bitmap bm = BitmapFactory.decodeFile(path, options); setInNativeAlloc(options); if (bm == null) { Log.e(TAG, "bitmap decode failed"); return null; } LogUtil.i(TAG, "bitmap decoded size=" + bm.getWidth() + "x" + bm.getHeight()); final Bitmap scale = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true); if (scale != null) { bm.recycle(); bm = scale; } if (crop) { final Bitmap cropped = Bitmap.createBitmap( bm, (bm.getWidth() - width) >> 1, (bm.getHeight() - height) >> 1, width, height); if (cropped == null) { return bm; } bm.recycle(); bm = cropped; LogUtil.i(TAG, "bitmap croped size=" + bm.getWidth() + "x" + bm.getHeight()); } return bm; } catch (final OutOfMemoryError e) { LogUtil.e(TAG, "decode bitmap failed: " + e.getMessage()); options = null; } return null; }
public void ApparelData(Context con, int act) { context = con; action = act; Apparel a = Controller.getInstance().getApparel(); Log.d("in apparel data", a.getApparel_name()); values = new ContentValues(); values.put(ApparelDB.ApparelTable.COLUMN_NAME_APPAREL_NAME, a.getApparel_name()); values.put(ApparelDB.ApparelTable.COLUMN_NAME_APPAREL_TYPE, a.getApparel_type()); // values.put(ApparelDB.ApparelTable.COLUMN_NAME_DRAWABLE_ID, a.getDrawable_id()); BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inScaled = true; opt.inMutable = true; /*if(a.getBlob_img_apparel()== null) { Bitmap imageBitmap1= BitmapFactory.decodeResource(context.getResources(), context.getResources().getIdentifier(a.getDrawable_id(), "drawable", context.getPackageName()), opt); ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); imageBitmap1.compress(Bitmap.CompressFormat.PNG, 100, bos1); byte[] bArray1 = bos1.toByteArray(); values.put(ApparelDB.ApparelTable.COLUMN_NAME_APPAREL_IMG, bArray1); } else { values.put(ApparelDB.ApparelTable.COLUMN_NAME_APPAREL_IMG,a.getBlob_img_apparel()); } if(a.getBlob_img_all_pieces()== null) { Bitmap imageBitmap2 = BitmapFactory.decodeResource(context.getResources(), context.getResources().getIdentifier(a.getPieces_Drawable_id(), "drawable", context.getPackageName()), opt); ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); imageBitmap2.compress(Bitmap.CompressFormat.PNG, 100, bos2); byte[] bArray2 = bos2.toByteArray(); values.put(ApparelDB.ApparelTable.COLUMN_NAME_ALL_PIECES_IMG, bArray2); } else { values.put(ApparelDB.ApparelTable.COLUMN_NAME_ALL_PIECES_IMG,a.getBlob_img_all_pieces()); }*/ values.put(ApparelDB.ApparelTable.COLUMN_NAME_APPAREL_IMG, a.getBlob_img_apparel()); values.put(ApparelDB.ApparelTable.COLUMN_NAME_ALL_PIECES_IMG, a.getBlob_img_all_pieces()); values.put(ApparelDB.ApparelTable.COLUMN_NAME_BOLT_WIDTH, a.getBolt_Width()); values.put(ApparelDB.ApparelTable.COLUMN_NAME_LENGTH, a.getLength()); values.put(ApparelDB.ApparelTable.COLUMN_NAME_NUM_PIECES, a.getNum_pieces()); Log.d("in apparel data", String.valueOf(a.getNum_pieces())); JSONArray jsonPatternTexts; JSONArray jsonPieces = new JSONArray(); JSONObject jsonPIObject, jsonPTObject; for (int i = 0; i < a.getNum_pieces(); i++) { Log.d("in apparel loop", String.valueOf(i)); Piece piece = a.getPieces().get(i); try { jsonPIObject = new JSONObject(); jsonPIObject.put("piece_shape", piece.getPiece_shape()); jsonPIObject.put("piece_fold", piece.getPiece_fold()); jsonPIObject.put("piece_height", piece.getPiece_height()); jsonPIObject.put("piece_width", piece.getPiece_width()); jsonPIObject.put("piece_info", piece.getPiece_info()); jsonPIObject.put("piece_image_id", piece.getPiece_image_id()); Bitmap image = BitmapFactory.decodeResource( context.getResources(), context .getResources() .getIdentifier( a.getPieces().get(i).getPiece_image_id(), "drawable", context.getPackageName()), opt); Log.d("apparel db image id", a.pieces.get(i).getPiece_image_id()); ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.PNG, 100, bos1); byte[] bArray = bos1.toByteArray(); String jsonString = Base64.encodeToString(bArray, Base64.DEFAULT); jsonPIObject.put("piece_image_blob", jsonString); Log.d("LOG", " json str" + jsonString.toString()); jsonPatternTexts = new JSONArray(); for (int k = 0; k < piece.getPatternTexts().size(); k++) { PatternText pt = piece.getPatternTexts().get(k); jsonPTObject = new JSONObject(); jsonPTObject.put("r", pt.getR()); jsonPTObject.put("angle", pt.getAngle()); jsonPTObject.put("x", pt.getX()); jsonPTObject.put("y", pt.getY()); jsonPatternTexts.put(jsonPTObject); Log.d("jsonPTObject", jsonPTObject.toString()); Log.d("jsonPatterntexts array", jsonPatternTexts.toString()); } jsonPIObject.put("pattern_texts", jsonPatternTexts); jsonPieces.put(jsonPIObject); Log.d("jsonPIObject", jsonPIObject.toString()); Log.d("json Pieces", jsonPieces.toString()); } catch (JSONException e) { e.printStackTrace(); } } values.put(ApparelDB.ApparelTable.COLUMN_NAME_PIECES, jsonPieces.toString()); ConfirmDialog(context, printContentValues(values)); }
@SuppressLint({"NewApi", "NewApi", "NewApi"}) // to avoid Lint errors since Android SDK r20 @Override protected Bitmap doInBackground(String... params) { Bitmap result = null; if (params.length != 1) return result; String storagePath = params[0]; try { BitmapFactory.Options options = new Options(); options.inScaled = true; options.inPurgeable = true; options.inJustDecodeBounds = true; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) { options.inPreferQualityOverSpeed = false; } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { options.inMutable = false; } result = BitmapFactory.decodeFile(storagePath, options); options.inJustDecodeBounds = false; int width = options.outWidth; int height = options.outHeight; int scale = 1; if (width >= 2048 || height >= 2048) { scale = (int) Math.ceil((Math.ceil(Math.max(height, width) / 2048.))); options.inSampleSize = scale; } Display display = getActivity().getWindowManager().getDefaultDisplay(); Point size = new Point(); int screenwidth; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) { display.getSize(size); screenwidth = size.x; } else { screenwidth = display.getWidth(); } Log.e("ASD", "W " + width + " SW " + screenwidth); if (width > screenwidth) { scale = (int) Math.ceil((float) width / screenwidth); options.inSampleSize = scale; } result = BitmapFactory.decodeFile(storagePath, options); Log.e("ASD", "W " + options.outWidth + " SW " + options.outHeight); } catch (OutOfMemoryError e) { result = null; Log.e(TAG, "Out of memory occured for file with size " + storagePath); } catch (NoSuchFieldError e) { result = null; Log.e(TAG, "Error from access to unexisting field despite protection " + storagePath); } catch (Throwable t) { result = null; Log.e(TAG, "Unexpected error while creating image preview " + storagePath, t); } return result; }