从ImageView保存到文件时保留位图尺寸

时间:2018-07-10 23:03:20

标签: java android kotlin android-bitmap bitmapdrawable

我正在尝试将ImageView内部的可绘制对象保存到文件中。 我使用Glide这样将图像加载到ImageView中:

    Glide.with(context)
            //items[position] is a string that represents a url 
            .load(items[position])
            .listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                    holder.progressBar.visibility = View.GONE
                    return false
                }

                override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                    holder.progressBar.visibility = View.GONE
                    return false
                }

            })
            .into(holder.imageView)

如果ImageView包含GIF,则可以使用以下方法将其毫无问题地保存到文件中:

//In a typical use case, gifDrawable will equal holder.imageView.(gifDrawable.constantState.newDrawable().mutate()) as GifDrawable
private fun gifDrawableToFile(gifDrawable: GifDrawable, gifFile: File) {
    val byteBuffer = gifDrawable.buffer
    val output = FileOutputStream(gifFile)
    val bytes = ByteArray(byteBuffer.capacity())
    (byteBuffer.duplicate().clear() as ByteBuffer).get(bytes)
    output.write(bytes, 0, bytes.size)
    output.close()
}

但是,如果ImageView包含静态图片-使用以下方法将其保存到文件中时,尺寸不会保留:

//In a typical use case, bitmapDrawable will equal holder.imageView.drawable.constantState.newDrawable().mutate() as BitmapDrawable
bitmapDrawable.bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)

以上代码无法维持静态图像在imageview内部的尺寸。

例如-请注意GIF如何保持其在imageView内部的尺寸:

Screenshot_Of_Gif

但是请注意,静态图片的尺寸是如何急剧扩展的:

Screenshot_Of_Static_Image

(在这两个示例中,我都将文件发送到Facebook Messenger应用,该文件用于在聊天中显示图像)。

尽管我的代码示例在Kotlin中,但用Java回答也很有帮助。

更新1-我用以下代码打印了ImageView和位图的宽度,它们是相同的。

val bitmap = (holder.imageView.drawable as BitmapDrawable).bitmap
Log.d("APP","Bwidth: " + bitmap.width)
Log.d("APP","Bheight:" + bitmap.height)

Log.d("APP","Iwidth" + holder.imageView.width)
Log.d("PP","Iheight" + holder.imageView.height)

但是两个高度/宽度的输出分别为315和300。

更新2-

在将位图保存到这样的文件后,我打印了位图的宽度。宽度和高度仍然是315和300。

val bmOptions = BitmapFactory.Options()
val bitmap = BitmapFactory.decodeFile(imageFile.absolutePath, bmOptions)
Log.d("APP","Bitmap from file width: " + bitmap.width)
Log.d("APP","Bitmap from file height: " + bitmap.height)

0 个答案:

没有答案