java - 如何将图像(应该是精确大小)写入外部存储

标签 java android image file-handling

我正在编写一个程序,从资源/可绘制对象中读取图像并将其刷新到外部存储。我的问题是不同的设备对于同一图像消耗不同的内存,但是我需要内存消耗保持不变。例如,设备 1 显示的图像大小为 3MB,而设备 2 显示的图像大小为 4MB。下面是我的示例代码。 TIA

BitmapFactory.Options options = new BitmapFactory.Options();
//setting few options
//making sure that the getByteCount will always return the same value irrespective of the device
bm = BitmapFactory.decodeResource(res, R.drawable.image, options); 
bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream); //where outstream is where I need to store my image in the device filesystem

最佳答案

我可以假设您的设备具有不同的屏幕尺寸和密度。因此使用不同的资源。

为了获得特定屏幕尺寸的可绘制性,您可以使用以下代码:

Drawable drawable = resources.getDrawableForDensity(id, DisplayMetrics.DENSITY_XHIGH, theme);

此外,您可以尝试减小图像的大小:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = 3; 
BitmapFactory.decodeResource(getResources(), R.mipmap.hqimage, options);

但一般来说,您不能总是确定图像会消耗相同数量的内存,这取决于多种因素。

希望这有帮助。

关于java - 如何将图像(应该是精确大小)写入外部存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58087621/

相关文章:

ios - XCode 11.5 升级后不显示 React-Native Image

java - 在 Opencv 3.1 Java 中操作单个像素时如何防止或处理字节溢出和字节下溢

java - 包含来自 FXML 的 FontAwesomeFX 图标和字形

android - java.lang.NoSuchMethodError : No virtual method execute for HttpClientResponse 错误

android - 编辑文本样式

android - Android中SplashScreen后台运行代码的方法

java - POI 3.2 图像高度/宽度控制

java - 使用 Apache POI 读取 .xlsx 文件会给出 InvocationTargetException

java - 如何获取搜索结果中出现的术语集?

java - 类的构造函数参数是否也应该使用 Java Bean Validation API 注释进行注释?