@TargetApi(10) private Bitmap decodeRegionCrop(Bitmap croppedImage, Rect rect) { // Release memory now clearImageView(); InputStream is = null; try { is = getContentResolver().openInputStream(sourceUri); BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(is, false); final int width = decoder.getWidth(); final int height = decoder.getHeight(); if (exifRotation != 0) { // Adjust crop area to account for image rotation Matrix matrix = new Matrix(); matrix.setRotate(-exifRotation); RectF adjusted = new RectF(); matrix.mapRect(adjusted, new RectF(rect)); // Adjust to account for origin at 0,0 adjusted.offset(adjusted.left < 0 ? width : 0, adjusted.top < 0 ? height : 0); rect = new Rect( (int) adjusted.left, (int) adjusted.top, (int) adjusted.right, (int) adjusted.bottom); } try { croppedImage = decoder.decodeRegion(rect, new BitmapFactory.Options()); } catch (IllegalArgumentException e) { // Rethrow with some extra information throw new IllegalArgumentException( "Rectangle " + rect + " is outside of the image (" + width + "," + height + "," + exifRotation + ")", e); } } catch (IOException e) { Log.e("Error cropping image: " + e.getMessage(), e); finish(); } catch (OutOfMemoryError e) { Log.e("OOM cropping image: " + e.getMessage(), e); setResultException(e); } finally { CropUtil.closeSilently(is); } return croppedImage; }
public static BitmapRegionDecoder createBitmapRegionDecoder( JobContext jc, FileDescriptor fd, boolean shareable) { try { return BitmapRegionDecoder.newInstance(fd, shareable); } catch (Throwable t) { Log.w(TAG, t); return null; } }
public static BitmapRegionDecoder createBitmapRegionDecoder( JobContext jc, String filePath, boolean shareable) { try { return BitmapRegionDecoder.newInstance(filePath, shareable); } catch (Throwable t) { Log.w(TAG, t); return null; } }
public static BitmapRegionDecoder createBitmapRegionDecoder( JobContext jc, InputStream is, boolean shareable) { try { return BitmapRegionDecoder.newInstance(is, shareable); } catch (Throwable t) { // We often cancel the creating of bitmap region decoder, // so just log one line. Log.w(TAG, "requestCreateBitmapRegionDecoder: " + t); return null; } }
private static Bitmap regionDecode( byte[] data, int reqWidth, int reqHeight, int outWidth, int outHeight) throws IOException { BitmapRegionDecoder regionDecoder = BitmapRegionDecoder.newInstance(data, 0, data.length, true); if (reqWidth > outWidth) { reqWidth = outWidth; } if (reqHeight > outHeight) { reqHeight = outHeight; } return regionDecoder.decodeRegion(new Rect(0, 0, reqWidth, reqHeight), null); }
@TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1) @Override protected BitmapRegionDecoder createBitmapRegionDecoder() { try { InputStream in = openInputStream(); if (in == null) { return null; } return BitmapRegionDecoder.newInstance(in, false); } catch (IOException e) { return null; } }
public static BitmapRegionDecoder createBitmapRegionDecoder( JobContext jc, byte[] bytes, int offset, int length, boolean shareable) { if (offset < 0 || length <= 0 || offset + length > bytes.length) { throw new IllegalArgumentException( String.format("offset = %s, length = %s, bytes = %s", offset, length, bytes.length)); } try { return BitmapRegionDecoder.newInstance(bytes, offset, length, shareable); } catch (Throwable t) { Log.w(TAG, t); return null; } }
public void setInputStream(InputStream is) { try { mDecoder = BitmapRegionDecoder.newInstance(is, false); BitmapFactory.Options tmpOptions = new BitmapFactory.Options(); // Grab the bounds for the scene dimensions tmpOptions.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, tmpOptions); mImageWidth = tmpOptions.outWidth; mImageHeight = tmpOptions.outHeight; requestLayout(); invalidate(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (Exception e) { } } }
public static HashMap<Character, Bitmap> getImages() { BitmapRegionDecoder decoder = null; if (sImages != null) return sImages; InputStream is = sContext.getResources().openRawResource(EN); try { decoder = BitmapRegionDecoder.newInstance(is, false); } catch (IOException ex) { } int h = decoder.getHeight(); sImages = new HashMap<Character, Bitmap>(); Rect r = new Rect(0, 0, h, h); for (char c = ABC.first(); c != CharacterIterator.DONE; c = ABC.next(), r.offset(h, 0)) { Bitmap bmp = decoder.decodeRegion(r, null); sImages.put(c, bmp); } Log.d("getImages", "float=" + sContext.getResources().getDisplayMetrics().density); return sImages; }
boolean decodeJPEGAndAnalyze(Context context, CalibrationEntries calibrationEntries) { boolean result = false; BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferQualityOverSpeed = true; BitmapRegionDecoder brd; byte[] data = mData; try { brd = BitmapRegionDecoder.newInstance(data, 0, data.length, false); Rect rect; rect = new Rect(0, 0, brd.getWidth(), brd.getHeight()); Bitmap bitmap = brd.decodeRegion(rect, opt); MatBitmapHolder mRgbaMatHolder = new MatBitmapHolder(bitmap); Mat rgbaMat = mRgbaMatHolder.pin(); Mat grayData = new Mat(); Imgproc.cvtColor(rgbaMat, grayData, Imgproc.COLOR_RGB2GRAY, 1); Mat centersCalibCircles = new Mat(); Size patternSize = CalibrationEntries.Pattern_ASYMMETRIC_CIRCLES_GRID_SIZE; Size imageSize = new Size(grayData.cols(), grayData.rows()); boolean patternWasFound = Calib3d.findCirclesGridDefault( grayData, patternSize, centersCalibCircles, Calib3d.CALIB_CB_ASYMMETRIC_GRID); if (patternWasFound && this.orientation != null) { int addedIdx = calibrationEntries.addEntry(this.orientation, centersCalibCircles); if (addedIdx >= 0) { Log.d( "CALIB", String.format( "PictureCapture: Added calibration entry at %d tot: %d", addedIdx, calibrationEntries.getNumEntries())); if (calibrationEntries.getNewlyAdded() > 5) { List<Mat> imagePoints = calibrationEntries.getPoints(); List<Mat> objectPoints = calibrationEntries.getObjectPointsAsymmentricList(imagePoints.size()); if (CalibrationEntries.isEnoughCalibrationPoints(imagePoints.size())) { calibrationEntries.resetNewlyAdded(); CameraCalibrationData cameraCalibrationData = new CameraCalibrationData(); List<Mat> rvecs = new Vector<Mat>(imagePoints.size()); List<Mat> tvecs = new Vector<Mat>(imagePoints.size()); int flags = 0; flags |= Calib3d.CALIB_FIX_K4 | Calib3d.CALIB_FIX_K5; Log.d("CALIB", String.format("PictureCapture: Calling Calib3d.calibrateCamera")); Mat K = new Mat(); Mat kdist = new Mat(); double rms = Calib3d.calibrateCamera( objectPoints, imagePoints, imageSize, K, kdist, rvecs, tvecs, flags); double[] Karray = new double[9]; double[] distcoeffs_array = new double[5]; K.get(0, 0, Karray); kdist.get(0, 0, distcoeffs_array); cameraCalibrationData.setData( grayData.cols(), grayData.rows(), Karray, distcoeffs_array, rms); Log.d( "CALIB", String.format( "PictureCapture: Calibration data: %s", cameraCalibrationData.formatCalibrationDataString())); calibrationEntries.setCalibrationData(cameraCalibrationData); result = true; } } } } // mRightBitmap = brd.decodeRegion(rect, opt); rect = new Rect(brd.getWidth() - brd.getWidth() / 3, 0, brd.getWidth(), brd.getHeight()); // mLeftBitmap = brd.decodeRegion(rect, opt); mRgbaMatHolder.unpin(rgbaMat); } catch (IOException e) { XLog.e("Region decoder doesn't want to cooperate", e); } return result; }
public static Bitmap getMiddlePictureInTimeLine( String url, int reqWidth, int reqHeight, FileDownloaderHttpHelper.DownloadListener downloadListener) { // int useWidth = 400; int useWidth = reqWidth; String absoluteFilePath = FileManager.getFilePathFromUrl(url, FileLocationMethod.picture_bmiddle); File file = new File(absoluteFilePath); if (!file.exists() && !SettingUtility.isEnablePic()) { return null; } if (!file.exists()) { getBitmapFromNetWork(url, absoluteFilePath, downloadListener); } if (absoluteFilePath.endsWith(".gif")) { return getMiddlePictureInTimeLineGif(absoluteFilePath, reqWidth, reqHeight); } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(absoluteFilePath, options); int height = options.outHeight; int width = options.outWidth; int cutHeight = 0; int cutWidth = 0; if (height >= reqHeight && width >= useWidth) { cutHeight = reqHeight; cutWidth = useWidth; } else if (height < reqHeight && width >= useWidth) { cutHeight = height; cutWidth = (useWidth * cutHeight) / reqHeight; } else if (height >= reqHeight && width < useWidth) { cutWidth = width; cutHeight = (reqHeight * cutWidth) / useWidth; } else if (height < reqHeight && width < useWidth) { float betweenWidth = ((float) useWidth - (float) width) / (float) width; float betweenHeight = ((float) reqHeight - (float) height) / (float) height; if (betweenWidth > betweenHeight) { cutWidth = width; cutHeight = (reqHeight * cutWidth) / useWidth; } else { cutHeight = height; cutWidth = (useWidth * cutHeight) / reqHeight; } } if (cutWidth > 0 && cutHeight > 0) { int startX = 0; if (cutWidth < width) { startX = (width - cutWidth) / 2; } try { BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(absoluteFilePath, false); if (decoder != null) { Bitmap region = decoder.decodeRegion(new Rect(startX, 0, startX + cutWidth, cutHeight), null); Bitmap scale = null; if (region.getHeight() < reqHeight && region.getWidth() < reqWidth) { scale = Bitmap.createScaledBitmap(region, reqWidth, reqHeight, true); } if (scale == null) { Bitmap anotherValue = ImageEdit.getRoundedCornerBitmap(region); region.recycle(); return anotherValue; // return region; } else { Bitmap anotherValue = ImageEdit.getRoundedCornerBitmap(scale); region.recycle(); scale.recycle(); return anotherValue; // return scale; } } } catch (IOException ignored) { // do nothing } } return null; }
public static Bitmap getMiddlePictureInTimeLine( String url, int reqWidth, int reqHeight, FileDownloaderHttpHelper.DownloadListener downloadListener) { try { String filePath = FileManager.getFilePathFromUrl(url, FileLocationMethod.picture_bmiddle); File file = new File(filePath); if (!file.exists() && !SettingUtility.isEnablePic()) { return null; } if (!file.exists()) { getBitmapFromNetWork(url, filePath, downloadListener); } if (isGif(filePath)) { return getMiddlePictureInTimeLineGif(filePath, reqWidth, reqHeight); } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); int height = options.outHeight; int width = options.outWidth; int cutHeight = 0; int cutWidth = 0; if (height >= reqHeight && width >= reqWidth) { cutHeight = reqHeight; cutWidth = reqWidth; } else if (height < reqHeight && width >= reqWidth) { cutHeight = height; cutWidth = (reqWidth * cutHeight) / reqHeight; } else if (height >= reqHeight && width < reqWidth) { cutWidth = width; cutHeight = (reqHeight * cutWidth) / reqWidth; } else if (height < reqHeight && width < reqWidth) { float betweenWidth = ((float) reqWidth - (float) width) / (float) width; float betweenHeight = ((float) reqHeight - (float) height) / (float) height; if (betweenWidth > betweenHeight) { cutWidth = width; cutHeight = (reqHeight * cutWidth) / reqWidth; } else { cutHeight = height; cutWidth = (reqWidth * cutHeight) / reqHeight; } } if (cutWidth > 0 && cutHeight > 0) { int startX = 0; if (cutWidth < width) { startX = (width - cutWidth) / 2; } try { BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(filePath, false); if (decoder != null) { Bitmap bitmap = decoder.decodeRegion(new Rect(startX, 0, startX + cutWidth, cutHeight), null); if (bitmap.getHeight() < reqHeight && bitmap.getWidth() < reqWidth) { Bitmap scale = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, true); if (scale != bitmap) { bitmap.recycle(); bitmap = scale; } } if (bitmap != null) { Bitmap roundedCornerBitmap = ImageEdit.getRoundedCornerBitmap(bitmap); if (roundedCornerBitmap != bitmap) { bitmap.recycle(); bitmap = roundedCornerBitmap; } return bitmap; } } } catch (IOException ignored) { } } return null; } catch (OutOfMemoryError ignored) { ignored.printStackTrace(); return null; } }
public boolean cropBitmap() { boolean failure = false; WallpaperManager wallpaperManager = null; if (mSetWallpaper) { wallpaperManager = WallpaperManager.getInstance(mContext.getApplicationContext()); } if (mSetWallpaper && mNoCrop) { try { InputStream is = regenerateInputStream(); if (is != null) { wallpaperManager.setStream(is); Utils.closeSilently(is); } } catch (IOException e) { Log.w(LOGTAG, "cannot write stream to wallpaper", e); failure = true; } return !failure; } else { // Find crop bounds (scaled to original image size) Rect roundedTrueCrop = new Rect(); Matrix rotateMatrix = new Matrix(); Matrix inverseRotateMatrix = new Matrix(); Point bounds = getImageBounds(); if (mRotation > 0) { rotateMatrix.setRotate(mRotation); inverseRotateMatrix.setRotate(-mRotation); mCropBounds.roundOut(roundedTrueCrop); mCropBounds = new RectF(roundedTrueCrop); if (bounds == null) { Log.w(LOGTAG, "cannot get bounds for image"); failure = true; return false; } float[] rotatedBounds = new float[] {bounds.x, bounds.y}; rotateMatrix.mapPoints(rotatedBounds); rotatedBounds[0] = Math.abs(rotatedBounds[0]); rotatedBounds[1] = Math.abs(rotatedBounds[1]); mCropBounds.offset(-rotatedBounds[0] / 2, -rotatedBounds[1] / 2); inverseRotateMatrix.mapRect(mCropBounds); mCropBounds.offset(bounds.x / 2, bounds.y / 2); } mCropBounds.roundOut(roundedTrueCrop); if (roundedTrueCrop.width() <= 0 || roundedTrueCrop.height() <= 0) { Log.w(LOGTAG, "crop has bad values for full size image"); failure = true; return false; } // See how much we're reducing the size of the image int scaleDownSampleSize = Math.max( 1, Math.min( roundedTrueCrop.width() / mOutWidth, roundedTrueCrop.height() / mOutHeight)); // Attempt to open a region decoder BitmapRegionDecoder decoder = null; InputStream is = null; try { is = regenerateInputStream(); if (is == null) { Log.w(LOGTAG, "cannot get input stream for uri=" + mInUri.toString()); failure = true; return false; } decoder = BitmapRegionDecoder.newInstance(is, false); Utils.closeSilently(is); } catch (IOException e) { Log.w(LOGTAG, "cannot open region decoder for file: " + mInUri.toString(), e); } finally { Utils.closeSilently(is); is = null; } Bitmap crop = null; if (decoder != null) { // Do region decoding to get crop bitmap BitmapFactory.Options options = new BitmapFactory.Options(); if (scaleDownSampleSize > 1) { options.inSampleSize = scaleDownSampleSize; } crop = decoder.decodeRegion(roundedTrueCrop, options); decoder.recycle(); } if (crop == null) { // BitmapRegionDecoder has failed, try to crop in-memory is = regenerateInputStream(); Bitmap fullSize = null; if (is != null) { BitmapFactory.Options options = new BitmapFactory.Options(); if (scaleDownSampleSize > 1) { options.inSampleSize = scaleDownSampleSize; } fullSize = BitmapFactory.decodeStream(is, null, options); Utils.closeSilently(is); } if (fullSize != null) { // Find out the true sample size that was used by the decoder scaleDownSampleSize = bounds.x / fullSize.getWidth(); mCropBounds.left /= scaleDownSampleSize; mCropBounds.top /= scaleDownSampleSize; mCropBounds.bottom /= scaleDownSampleSize; mCropBounds.right /= scaleDownSampleSize; mCropBounds.roundOut(roundedTrueCrop); // Adjust values to account for issues related to rounding if (roundedTrueCrop.width() > fullSize.getWidth()) { // Adjust the width roundedTrueCrop.right = roundedTrueCrop.left + fullSize.getWidth(); } if (roundedTrueCrop.right > fullSize.getWidth()) { // Adjust the left value int adjustment = roundedTrueCrop.left - Math.max(0, roundedTrueCrop.right - roundedTrueCrop.width()); roundedTrueCrop.left -= adjustment; roundedTrueCrop.right -= adjustment; } if (roundedTrueCrop.height() > fullSize.getHeight()) { // Adjust the height roundedTrueCrop.bottom = roundedTrueCrop.top + fullSize.getHeight(); } if (roundedTrueCrop.bottom > fullSize.getHeight()) { // Adjust the top value int adjustment = roundedTrueCrop.top - Math.max(0, roundedTrueCrop.bottom - roundedTrueCrop.height()); roundedTrueCrop.top -= adjustment; roundedTrueCrop.bottom -= adjustment; } crop = Bitmap.createBitmap( fullSize, roundedTrueCrop.left, roundedTrueCrop.top, roundedTrueCrop.width(), roundedTrueCrop.height()); } } if (crop == null) { Log.w(LOGTAG, "cannot decode file: " + mInUri.toString()); failure = true; return false; } if (mOutWidth > 0 && mOutHeight > 0 || mRotation > 0) { float[] dimsAfter = new float[] {crop.getWidth(), crop.getHeight()}; rotateMatrix.mapPoints(dimsAfter); dimsAfter[0] = Math.abs(dimsAfter[0]); dimsAfter[1] = Math.abs(dimsAfter[1]); if (!(mOutWidth > 0 && mOutHeight > 0)) { mOutWidth = Math.round(dimsAfter[0]); mOutHeight = Math.round(dimsAfter[1]); } RectF cropRect = new RectF(0, 0, dimsAfter[0], dimsAfter[1]); RectF returnRect = new RectF(0, 0, mOutWidth, mOutHeight); Matrix m = new Matrix(); if (mRotation == 0) { m.setRectToRect(cropRect, returnRect, Matrix.ScaleToFit.FILL); } else { Matrix m1 = new Matrix(); m1.setTranslate(-crop.getWidth() / 2f, -crop.getHeight() / 2f); Matrix m2 = new Matrix(); m2.setRotate(mRotation); Matrix m3 = new Matrix(); m3.setTranslate(dimsAfter[0] / 2f, dimsAfter[1] / 2f); Matrix m4 = new Matrix(); m4.setRectToRect(cropRect, returnRect, Matrix.ScaleToFit.FILL); Matrix c1 = new Matrix(); c1.setConcat(m2, m1); Matrix c2 = new Matrix(); c2.setConcat(m4, m3); m.setConcat(c2, c1); } Bitmap tmp = Bitmap.createBitmap( (int) returnRect.width(), (int) returnRect.height(), Bitmap.Config.ARGB_8888); if (tmp != null) { Canvas c = new Canvas(tmp); Paint p = new Paint(); p.setFilterBitmap(true); c.drawBitmap(crop, m, p); crop = tmp; } } if (mSaveCroppedBitmap) { mCroppedBitmap = crop; } // Get output compression format CompressFormat cf = convertExtensionToCompressFormat(getFileExtension(mOutputFormat)); // Compress to byte array ByteArrayOutputStream tmpOut = new ByteArrayOutputStream(2048); if (crop.compress(cf, DEFAULT_COMPRESS_QUALITY, tmpOut)) { // If we need to set to the wallpaper, set it if (mSetWallpaper && wallpaperManager != null) { try { byte[] outByteArray = tmpOut.toByteArray(); wallpaperManager.setStream(new ByteArrayInputStream(outByteArray)); if (mOnBitmapCroppedHandler != null) { mOnBitmapCroppedHandler.onBitmapCropped(outByteArray); } } catch (IOException e) { Log.w(LOGTAG, "cannot write stream to wallpaper", e); failure = true; } } } else { Log.w(LOGTAG, "cannot compress bitmap"); failure = true; } } return !failure; // True if any of the operations failed }