欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

解决Android BitmapFactory的基本使用问题

程序员文章站 2022-06-17 22:33:34
问题描述使用方法bitmapfactory.decodefile转化bitmap时报错:java.lang.runtimeexception: canvas: trying to draw too l...

问题描述

使用方法bitmapfactory.decodefile转化bitmap时报错:java.lang.runtimeexception: canvas: trying to draw too large(120422400bytes) bitmap.

解决方案

报错原因:图片转化为bitmap超过最大值max_bitmap_size

frameworks/base/graphics/java/android/graphics/recordingcanvas.java

public static final int max_bitmap_size = 100 * 1024 * 1024; // 100 mb

/** @hide */
@override
protected void throwifcannotdraw(bitmap bitmap) {
    super.throwifcannotdraw(bitmap);
    int bitmapsize = bitmap.getbytecount();
    if (bitmapsize > max_bitmap_size) {
        throw new runtimeexception(
                "canvas: trying to draw too large(" + bitmapsize + "bytes) bitmap.");
    }
}

修改如下

//修改前
bitmap image = bitmapfactory.decodefile(filepath);
imageview.setimagebitmap(image);

//修改后
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.util.displaymetrics;

file file = new file(filepath);
if (file.exists() && file.length() > 0) {
    //获取设备屏幕大小
    displaymetrics dm = getresources().getdisplaymetrics();
    int screenwidth = dm.widthpixels;
    int screenheight = dm.heightpixels;
    //获取图片宽高
    bitmapfactory.options options = new bitmapfactory.options();
    options.injustdecodebounds = true;	
    bitmapfactory.decodefile(filepath, options);	
    float srcwidth = options.outwidth;	
    float srcheight = options.outheight;	
    //计算缩放比例
    int insamplesize = 1;	
    if (srcheight > screenheight || srcwidth > screenwidth) {	
        if (srcwidth > srcheight) {	
            insamplesize = math.round(srcheight / screenheight);	
        } else {	
            insamplesize = math.round(srcwidth / screenwidth);	
        }	
    }	
    options.injustdecodebounds = false;	
    options.insamplesize = insamplesize;	
    
    bitmap bitmap = bitmapfactory.decodefile(filepath, options);	
    imageview.setimagebitmap(bitmap);
}

相关参考:

android 图片缓存之 bitmap 详解
https://juejin.cn/post/6844903442939412493

bitmapfactory
https://developer.android.com/reference/android/graphics/bitmapfactory.html

bitmapfactory.options
bitmapfactory.options类是bitmapfactory对图片进行解码时使用的一个配置参数类,其中定义了一系列的public成员变量,每个成员变量代表一个配置参数。
https://blog.csdn.net/showdy/article/details/54378637

到此这篇关于android bitmapfactory的基本使用的文章就介绍到这了,更多相关android bitmapfactory使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!