Dealing with large bitmap onPictureTaken android

女生的网名这么多〃 提交于 2020-01-02 23:50:34

问题


My app is an OCR app base on Tesseract. It will do OCR task from camera picture. Users can take many pictures and put them into an OCR queue. To get more accuracy, I want to keep high quality image (I choose min size is 1024 x 768 (maybe larger in future), JPEG, 100% quality). When users take many pictures, there are three things to do:

  1. Save the image data byte[] to file and correct EXIF.
  2. Correct the image orientation base on device's orientation. I know there are some answers that said the image which comes out of the camera is not oriented automatically, have to correct it from file, like here and here. I'm not sure about it, I can setup the camera preview orientation correctly, but the image results aren't correct.
  3. Load bitmap from taken picture, convert it to grayscale and save to another file for OCR task.

And here is my try:

public static boolean saveBitmap(byte[] bitmapData, int orientation, String imagePath, String grayScalePath) throws Exception {
    Boolean rotationSuccess = false;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap originalBm = null;
    Bitmap bitmapRotate = null;
    Bitmap grayScale = null;
    FileOutputStream outStream = null;
    try {
          // save directly from byte[] to file
        saveBitmap(bitmapData, imagePath);

          // down sample
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, options);
        int sampleSize = calculateInSampleSize(options, Config.CONFIG_IMAGE_WIDTH, Config.CONFIG_IMAGE_HEIGHT);
        options.inJustDecodeBounds = false;
        options.inSampleSize = sampleSize;

        originalBm = BitmapFactory.decodeFile(imagePath, options);
        Matrix mat = new Matrix();
        mat.postRotate(orientation);
        bitmapRotate = Bitmap.createBitmap(originalBm, 0, 0, originalBm.getWidth(), originalBm.getHeight(), mat, true);
        originalBm.recycle();
        originalBm = null;

        outStream = new FileOutputStream(new File(imagePath));
        bitmapRotate.compress(CompressFormat.JPEG, 100, outStream);

        // convert to gray scale
         grayScale = UIUtil.convertToGrayscale(bitmapRotate);
        saveBitmap(grayScale, grayScalePath);
        grayScale.recycle();
        grayScale = null;

        bitmapRotate.recycle();
        bitmapRotate = null;
        rotationSuccess = true;
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        System.gc();
    } finally {
        if (originalBm != null) {
            originalBm.recycle();
            originalBm = null;
        }

        if (bitmapRotate != null) {
            bitmapRotate.recycle();
            bitmapRotate = null;
        }

        if (grayScale != null) {
            grayScale.recycle();
            grayScale = null;
        }

        if (outStream != null) {
            try {
                outStream.close();
            } catch (IOException e) {
            }
            outStream = null;
        }
    }

            Log.d(TAG,"save completed");
    return rotationSuccess;
}

Save to file directly from byte[]

   public static void saveBitmap(byte[] bitmapData, String fileName) throws Exception {
    File file = new File(fileName);
    FileOutputStream fos;
    BufferedOutputStream bos = null;
    try {
        final int bufferSize = 1024 * 4;
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos, bufferSize);
        bos.write(bitmapData);
        bos.flush();
    } catch (Exception ex) {
        throw ex;
    } finally {
        if (bos != null) {
            bos.close();
        }
    }
}

Calculate scale size

    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    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;

        // Calculate the largest inSampleSize value that is a power of 2 and
        // keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

When save complete, this image is loaded into thumbnail image view by UIL. The problem is the save task is very slow (wait some second before save complete and load into view), and sometime I got OutOfMemory exception.
Is there any ideas to reduce the save task and avoid OutOfMemory exception?
Any help would be appreciated!

P/S: the first time I try to convert byte[] to bitmap instead of save to file, and then rotate and convert to grayscale, but I still got above issues.
Update: here is the grayscale bitmap process:

   public static Bitmap convertToGrayscale(Bitmap bmpOriginal) {
    int width, height;
    height = bmpOriginal.getHeight();
    width = bmpOriginal.getWidth();    

    Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(bmpGrayscale);
    Paint paint = new Paint();
    ColorMatrix cm = new ColorMatrix();
    cm.setSaturation(0);
    ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
    paint.setColorFilter(f);
    c.drawBitmap(bmpOriginal, 0, 0, paint);
    return bmpGrayscale;
}

The OutOfMemory exception seldom occurred (just a few times) and I can't reproduce it now.


回答1:


Update: Since you're still saying that the method takes too long time I would define a callback interface

interface BitmapCallback {
    onBitmapSaveComplete(Bitmap bitmap, int orientation);

    onBitmapRotateAndBWComlete(Bitmap bitmap);
}

Let your activity implement the above interface and convert the byte[] to bitmap in top of your saveBitmap method and fire the callback, before the first call to save. Rotate the imageView based on the orientation parameter and set a black/white filter on the imageView to fool the user into thinking that the bitmap is black and white (do this in your activity). See to that the calls are done on main thread (the calls to imageView). Keep your old method as you have it. (all steps need to be done anyway) Something like:

public static boolean saveBitmap(byte[] bitmapData, int orientation, String imagePath, String grayScalePath, BitmapCallback callback) throws Exception {
Boolean rotationSuccess = false;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap originalBm = null;
Bitmap bitmapRotate = null;
Bitmap grayScale = null;
FileOutputStream outStream = null;
try {
    // TODO: convert byte to Bitmap, see to that the image is not larger than your wanted size (1024z768)
    callback.onBitmapSaveComplete(bitmap, orientation);

    // save directly from byte[] to file
    saveBitmap(bitmapData, imagePath);
    .
    .
    // same as old 
    .
    .
    saveBitmap(grayScale, grayScalePath);
    // conversion done callback with the real fixed bitmap
    callback.onBitmapRotateAndBWComlete(grayScale);

    grayScale.recycle();
    grayScale = null;

    bitmapRotate.recycle();
    bitmapRotate = null;
    rotationSuccess = true;
  1. How do you setup your camera? What might be causing the long execution time in the first saveBitmap call, could be that you are using the default camera picture size settings and not reading the supported camera picture size and choosing best fit for your 1024x768 image needs. You might be taking big mpixel images and saving such, but in the end need you need < 1 mpixles (1024x768). Something like this in code:

    Camera camera = Camera.open();
    Parameters params = camera.getParameters();
    List sizes = params.getSupportedPictureSizes();
    // Loop camera sizes and find best match, larger than 1024x768

    This is probably where you will save most of the time if you are not doing this already. And do it only once, during some initialization phase.

  2. Increase the buffer to 8k in saveBitmap, change the 1024*4 to 1024*8, this would increase the performance at least, not save any significant time perhaps.

  3. To save/reuse bitmap memory consider using inBitmap field, if you have a post honeycomb version, of BitmapFactory.Options and set that field to point to bitmapRotate bitmap and send options down to your convertToGrayscale method to not need allocating yet another bitmap down in that method. Read about inBitmap here: inBitmap



来源:https://stackoverflow.com/questions/20870075/dealing-with-large-bitmap-onpicturetaken-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!