原始文件中的预览文件的 Android 位图尺寸更大
给定 Android 中的一个文件(当然是一个图像),我想制作一个预览图像,它的尺寸当然应该更小。我使用下面的代码
override fun createImagePreview(serverId: Long, fileName: String) {
if (fileName.fileType() != IMAGE_TYPE) return
val file = serverDir.getFileByName(fileName)
val originalBitmap = BitmapFactory.decodeFile(file.absolutePath) ?: return
var newWidth = DEFAULT_IMAGE_SIZE.toDouble()
var newHeight = DEFAULT_IMAGE_SIZE.toDouble()
if (originalBitmap.width > originalBitmap.height) {
val ratio = originalBitmap.width / originalBitmap.height
newHeight = newWidth / ratio
} else if (originalBitmap.width < originalBitmap.height) {
val ratio = originalBitmap.height / originalBitmap.width
newWidth = newHeight / ratio
}
val bmp = ThumbnailUtils.extractThumbnail(
originalBitmap,
newWidth.toInt().dpToPixel(appContext),
newHeight.toInt().dpToPixel(appContext)
)
FileOutputStream(File(serverDir, "p_$fileName")).use {
it.write(bmp.toByteArray())
it.flush()
}
}
但是,我在内部存储中看到,如果文件为 5KB,则预览文件为 19KB。这有什么问题吗?
Given a file (which of course is an Image) in Android i want to make a preview image which of course should be smaller in size. I use the code below
override fun createImagePreview(serverId: Long, fileName: String) {
if (fileName.fileType() != IMAGE_TYPE) return
val file = serverDir.getFileByName(fileName)
val originalBitmap = BitmapFactory.decodeFile(file.absolutePath) ?: return
var newWidth = DEFAULT_IMAGE_SIZE.toDouble()
var newHeight = DEFAULT_IMAGE_SIZE.toDouble()
if (originalBitmap.width > originalBitmap.height) {
val ratio = originalBitmap.width / originalBitmap.height
newHeight = newWidth / ratio
} else if (originalBitmap.width < originalBitmap.height) {
val ratio = originalBitmap.height / originalBitmap.width
newWidth = newHeight / ratio
}
val bmp = ThumbnailUtils.extractThumbnail(
originalBitmap,
newWidth.toInt().dpToPixel(appContext),
newHeight.toInt().dpToPixel(appContext)
)
FileOutputStream(File(serverDir, "p_$fileName")).use {
it.write(bmp.toByteArray())
it.flush()
}
}
However, i see inside my internalStorage that if the File is 5KB then the PreviewFile is 19KB. What is wrong with that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
bmp.toByteArray 是存储图像的错误方法。 Bitmap 对象未压缩。这意味着每个像素使用 4 个字节。 jpg 或 png 是经过压缩的,这意味着它每个像素使用的数据更少。您想将其存储为其中一种格式。执行此操作的方法是使用 Bitmap.compress() 并将其传递到要使用的文件的流。
bmp.toByteArray is the wrong way to store an image. The Bitmap object is uncompressed. That means it uses 4 bytes per pixel. A jpg or png is compressed, that means it uses less data per pixel. You want to store it in one of those formats. The way to do that is to use Bitmap.compress() and pass it a stream to the file you want to use.