Android中解码部分JPEG字节数组的方法
我正在开发一个 Android 应用程序,其中有一个 JPEG 图像的字节数组,需要显示它。目前,我正在 Android 中使用以下代码对其进行解码:
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
ImageView imageDisplay = findViewById(R.id.image_display);
imageDisplay.setImageBitmap(bitmap);
如果我有完整的图像,这效果很好。但是,如果我取出字节数组并砍掉它的最后 25%,BitmapFactory.decodeByteArray
将返回 null
。根据 文档< /a>,方法 BitmapFactory.decodeByteArray
返回:
解码后的位图,如果图像无法解码,则为 null。
这让我感到惊讶,因为我认为部分 JPEG可以被解码。作为实验,我在十六进制编辑器中打开了 JPEG,并将其缩小为原始大小的 75%、50% 和 25%,并且在所有情况下,Windows 仍然能够显示图像(我能够也可以在 Paint.NET 中打开每个图像!)
如果我将图像保存为“渐进式”JPEG,性能会更好!下面的 partial-25.jpg 文件只是原始文件字节的前四分之一,但显示效果相当好。如果放大的话,细节会少一些,但还是不错的!
我正在 Android 中寻找同样的行为。当遇到提前结束的 JPEG 字节数组时,我想绘制到目前为止所拥有的任何内容。
是否有某种方法可以让 BitmapFactory.decodeByteArray
给我这种行为,或者是否有其他 Android 包含的方法可以做到这一点?如果没有,我愿意使用一个库。
(我这样做的原因是因为图像数据实际上到达非常慢(想想每秒字节数很慢) ,我想在它进来时就画它,而不是等到最后才画整个东西。)
I'm working on an Android app where I have a byte array of a JPEG image and need to display it. Currently, I'm decoding it in Android with this code:
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
ImageView imageDisplay = findViewById(R.id.image_display);
imageDisplay.setImageBitmap(bitmap);
This works great, if I have the full image. However, if I take the byte array and chop off, say, the final 25% of it, BitmapFactory.decodeByteArray
returns null
. According to the documentation, the method BitmapFactory.decodeByteArray
returns:
The decoded bitmap, or null if the image could not be decoded.
This surprises me because I thought partial JPEGs could be decoded. As an experiment, I opened a JPEG in a hex editor and chopped it down to 75%, 50%, and 25% of its original size, and, in all cases, Windows was still able to show the image (I was able to open each image in Paint.NET too!)
If I saved the image as a "progressive" JPEG, the performance was even better! Below, the partial-25.jpg file is only the first quarter of the original file's bytes, but it displays quite well. If you zoom in, there is less detail, but it's pretty good!
I'm looking for this same behavior in Android. When encountering a JPEG byte array that ends prematurely, I want to draw whatever I have so far.
Is there some way to get BitmapFactory.decodeByteArray
to give me this behavior, or is there another Android included method that could do so? If not, I'm willing to use a library for it.
(The reason I'm doing this is because the image data is actually arriving very slowly (think bytes per second slowly), and I'd like to draw it as it comes in, rather than waiting until the end to draw the whole thing.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论