gpt4 book ai didi

java - 将字节数组转换为位图在 java 中给出 bitmap=null

转载 作者:行者123 更新时间:2023-11-29 19:53:21 26 4
gpt4 key购买 nike

我正在尝试做一些非常简单的事情,但结果并不那么简单。我有一个位图图像,我必须将它转换为字节才能通过套接字发送。字节数组正确发送(我已经检查过),但是当我转换回位图时,我得到 bitmap=null 结果。我相信我的错误在于我如何将原始位图转换为字节,或者当我试图将我的字节转回位图时。

在调试过程中,我意识到如果我获取位图,将其转换为字节,然后将其直接转换回位图(不通过套接字发送),它也是空的。这是我的代码:如何将位图转换为字节,然后再将字节转换回位图图像?

        // I am getting my image from ApplicationInfo and I know I am getting it because I have opened it on my computer after extracting it
Drawable icon = context.getPackageManager().getApplicationIcon(ai);
Log.d("tag_name", "ICON" + icon);

BitmapDrawable bitmapIcon = (BitmapDrawable)icon;
Log.d("tag_name", "BITMAP Drawable" + bitmapIcon);

// STREAM IMAGE DATA TO FILE
// This is how I know I am correctly getting my png image (no errors here)

FileOutputStream fosIcon = context.openFileOutput(applicationName + ".png", Context.MODE_PRIVATE);

bitmapIcon.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, fosIcon);
InputStream inputStream = context.openFileInput(applicationName + ".png");

Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Log.d("tag_name", "BITMAP NAME" + bitmap);


// get bitmap image in bytes to send

int bytes = bitmap.getByteCount();
Log.d("tag_name", "Number of Bytes" + bytes);

ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
bitmap.copyPixelsToBuffer(buffer); //Move the byte data to the buffer

byte[] array = buffer.array();
Log.d("tag_name", "array" + array);
int start=0;
int len=array.length;
Log.d("tag_name", "length" + len);

if (len < 0)
throw new IllegalArgumentException("Negative length not allowed");
if (start < 0 || start >= array.length)
throw new IndexOutOfBoundsException("Out of bounds: " + start);


// Convert BACK TO bitmap (this will be done on the other side of my socket, but it is also null here???
Bitmap bitmap_2 = BitmapFactory.decodeByteArray(array , 0, array.length);
System.out.println("Bitmap Name 2" + bitmap_2);

// Open SendToClient Class to send string and image over socket

new SendToClient(array, applicationName, len, start, packagename).execute();

最佳答案

我在网上搜索了一下,最后发现有人遇到了同样的问题,即位图返回 null,下面是解决方法!出于某种原因,它首先将字节数组转换为 jpeg,然后再转换为位图:

// Convert data to jpeg first then to bitmap (cant convert byte array directly to bitmap)
YuvImage yuvimage=new YuvImage(data, ImageFormat.NV21, 100, 100, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, 100, 100), 80, baos);
byte[] jdata = baos.toByteArray();

// Convert to Bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
System.out.println("Bitmap Name 3" + bmp);

我在创建字节数组的地方添加了这段代码。所以我在这里称为“数据”的变量是字节数组。

关于java - 将字节数组转换为位图在 java 中给出 bitmap=null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36927299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com