gpt4 book ai didi

android - 如何在 Android 中将图像转换为字节数组

转载 作者:太空狗 更新时间:2023-10-29 14:20:22 25 4
gpt4 key购买 nike

我面临一个真正的问题。我需要将图像转换为字节数组格式,以便我可以将字节数组上传到网络服务器。我已经尝试了很多但是它不起作用。我也得到字节数组的负值。我不确定在数组中获取字节值我做错了什么。

下面是我的代码。请帮我看看我做错了什么?

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.home_menu_icon);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();

最佳答案

如果您的图像来自 GALLERY 和 CAMERA,我会在此处显示两者的代码

if (requestCode == IMAGE_PICKER_REQUEST && resultCode == RESULT_OK) {
fileName = getRealPathFromURI(data.getData());

try {
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(
data.getData());

bitmap = BitmapFactory.decodeStream(stream);
stream.close();
image.setImageBitmap(bitmap);
//picNameText.setText("Selected: en"
// + getStringNameFromRealPath(fileName));

ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream1);
imageInByte = stream1.toByteArray();

}catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}

if (requestCode == IMAGE_TAKER_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(photo);

ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream2);
imageInByte = stream2.toByteArray();

}

享受它为我工作......

关于android - 如何在 Android 中将图像转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17613228/

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