草庐IT

java - Android图片调整大小报错内存

coder 2023-12-14 原文

我有一个旋转图像的方法,但我总是收到 OutMemoryError,但我在图库中的图像是从相机拍摄的,尺寸宽度是 5000~ 来自手机

我将照片调整为宽度 1280 和高度 960

我第一个显示和调整图像大小的方法是

    public static Boolean ShowImagesCapture(Context context, Uri PATH_IMAGE, ImageCropView view,int width, int height){

    int orientation=0;
    Boolean success = true;
    try {
        Bitmap bitmap =null;

        if (Build.VERSION.SDK_INT < 19) {
            String selectedImagePath = getPath(PATH_IMAGE,context);
            bitmap = BitmapFactory.decodeFile(selectedImagePath);
            orientation=GetPhotoOrientation(context,getRealPathFromURI(context,PATH_IMAGE));
        }

        else {
            ParcelFileDescriptor parcelFileDescriptor;

            try {
                parcelFileDescriptor = context.getContentResolver().openFileDescriptor(PATH_IMAGE, "r");
                FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
                parcelFileDescriptor.close();
                orientation=GetPhotoOrientation(context,getRealPathFromURI(context,PATH_IMAGE));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        switch (orientation) {

            case ExifInterface.ORIENTATION_ROTATE_180:
                bitmap=rotateBitmap(bitmap,3,width,height);
                view.setImageBitmap(bitmap);

                break;
      break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                bitmap=rotateBitmap(bitmap,8,width,height);
                view.setImageBitmap(bitmap);
                break;

            case ExifInterface.ORIENTATION_TRANSVERSE:
                break;

            case ExifInterface.ORIENTATION_ROTATE_270:
                bitmap=rotateBitmap(bitmap,6,width,height);
                view.setImageBitmap(bitmap);
                break;

            default:
                view.setImageBitmap(bitmap);

        }

        bitmap = null;

    }
    catch (Exception e) {
        e.printStackTrace();
        success= false;
    }
    System.gc();
    return success;
}

我旋转图片的方法是

public static Bitmap rotateBitmap(Bitmap bitmap, int orientation,int width,int height) {

    try {
        Matrix matrix = new Matrix();
        switch (orientation) {
            case ExifInterface.ORIENTATION_NORMAL:
                return bitmap;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                //                matrix.setScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.setRotate(180);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                matrix.setRotate(180);
                //                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_TRANSPOSE:
                matrix.setRotate(90);
                //                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.setRotate(90);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:
                matrix.setRotate(-90);
                //                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.setRotate(-270);
                break;
            default:
                return bitmap;
        }



        Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
        bitmap.recycle();
        return bmRotated;

    }
    catch (OutOfMemoryError e) {
        Log.e(TAG,"Out memory Error");
        return null;
    }catch (Exception e){
        e.printStackTrace();
        return null;
    }
}

我的错误在哪里?

*--------------------** 2016 年 6 月 27 日更新 **-------------------- *

我的代码在最佳版本中运行良好

public static Bitmap rotateBitmap(Bitmap bitmap, int orientation,int width,int height) {

    try {
        Matrix matrix = new Matrix();
        switch (orientation) {
            case ExifInterface.ORIENTATION_NORMAL:
                return bitmap;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                matrix.setScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.setRotate(180);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                matrix.setRotate(180);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_TRANSPOSE:
                matrix.setRotate(90);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.setRotate(90);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:
                matrix.setRotate(-90);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.setRotate(-270);
                break;
            default:
                return bitmap;
        }
        Bitmap bmRotated= null;
        try {
            Bitmap tmp_bitmap= Bitmap.createScaledBitmap(bitmap,width,height,true);

            bmRotated = Bitmap.createBitmap(tmp_bitmap, 0, 0, tmp_bitmap.getWidth(),tmp_bitmap.getHeight(), matrix, true);

            bitmap.recycle();
        }catch (OutOfMemoryError e){
            e.printStackTrace();
        }
        return bmRotated;

    } catch (Exception e){
        e.printStackTrace();
        return null;
    }
}


 public static Bitmap decodefilebitmap(String selectedImagePath, int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(selectedImagePath, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(selectedImagePath, options);
}

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;
}

//METODO PARA MOSTRAR LA IMAGEN DESDE LA GALERIA
public static Boolean ShowImagesCapture(Context context, Uri PATH_IMAGE, ImageCropView view,int width, int height){

    int orientation=0;
    Boolean success = true;
    try {
        Bitmap bitmap =null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        if (Build.VERSION.SDK_INT < 19) {
            String selectedImagePath = getPath(PATH_IMAGE,context);
            bitmap = decodefilebitmap(selectedImagePath,bitmap.getWidth(),bitmap.getHeight());
            orientation=GetPhotoOrientation(context,getRealPathFromURI(context,PATH_IMAGE));
        }

        else {
            ParcelFileDescriptor parcelFileDescriptor;

            try {
                parcelFileDescriptor = context.getContentResolver().openFileDescriptor(PATH_IMAGE, "r");
                FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
                parcelFileDescriptor.close();
                orientation=GetPhotoOrientation(context,getRealPathFromURI(context,PATH_IMAGE));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        switch (orientation) {


            case ExifInterface.ORIENTATION_ROTATE_180:
                bitmap=rotateBitmap(bitmap,3,width,height);
                view.setImageBitmap(bitmap);

                break;

            case ExifInterface.ORIENTATION_ROTATE_90:
                bitmap=rotateBitmap(bitmap,8,width,height);
                view.setImageBitmap(bitmap);
                break;

            case ExifInterface.ORIENTATION_TRANSVERSE:
                break;

            case ExifInterface.ORIENTATION_ROTATE_270:
                bitmap=rotateBitmap(bitmap,6,width,height);
                view.setImageBitmap(bitmap);
                break;

            default:
                view.setImageBitmap(bitmap);

        }

        bitmap = null;

    }
    catch (Exception e) {
        e.printStackTrace();
        success= false;
    }
    System.gc();
    return success;
}

最佳答案

那是因为你正在将整个位图加载到内存中 bitmap = BitmapFactory.decodeFile(selectedImagePath); 然后将调整大小的版本显示到 ImageView 中(但浪费内存,因为你有完整大小的版本内存)。您需要加载缩小版本。加载所有位图然后对其执行操作(缩放、旋转、将其放入 ImageView )与将该位图的缩小版本加载到内存中是不同的。例如,如果您有一张 5000 x 5000 像素的图像,假设 JPEG 格式的图像大小约为 1MB。但是当你将它加载到内存中时,你解压缩它并加载该图像的整个未压缩版本。假设您以每像素 32 位加载它,那么它在 RAM 中的大小将为 5000x5000x32 位,即大约 95MB!所以你需要加载一个按比例缩小的版本。查看此 Android 开发人员文档 about loading a scaled down bitmap version into memory .这将帮助您更好地理解问题。您还可以使用图像加载库,如 Glide .这些库可以完成所有这一切,甚至更多。

关于java - Android图片调整大小报错内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38058922/

有关java - Android图片调整大小报错内存的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  3. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  4. ruby-on-rails - Ruby 中的内存模型 - 2

    ruby如何管理内存。例如:如果我们在执行过程中采用C程序,则以下是内存模型。类似于这个ruby如何处理内存。C:__________________|||stack|||------------------||||------------------|||||Heap|||||__________________|||data|__________________|text|__________________Ruby:? 最佳答案 Ruby中没有“内存”这样的东西。Class#allocate分配一个对象并返回该对象。这就是程序

  5. ruby-on-rails - Ruby on Rails - 为文本区域和图片生成列 - 2

    我是Rails的新手,所以请原谅简单的问题。我正在为一家公司创建一个网站。那家公司想在网站上展示它的客户。我想让客户自己管理这个。我正在为“客户”生成一个表格,我想要的三列是:公司名称、公司描述和Logo。对于名称,我使用的是name:string但不确定如何在脚本/生成脚手架终端命令中最好地创建描述列(因为我打算将其设置为文本区域)和图片。我怀疑描述(我想成为一个文本区域)应该仍然是描述:字符串,然后以实际形式进行调整。不确定如何处理图片字段。那么……说来话长:我在脚手架命令中输入什么来生成描述和图片列? 最佳答案 对于“文本”数

  6. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  7. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  8. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  9. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

  10. 【Java 面试合集】HashMap中为什么引入红黑树,而不是AVL树呢 - 2

    HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候

随机推荐