我想将一个字符串URL转换为图片。尽管存在包含图片的URL,但它返回null。我在下面分享了代码。
private byte[] convertImageToByteArray(String imgPath)
{
byte[] byteArray = null;
Bitmap bmp = BitmapFactory.decodeFile(imgPath);
if(bmp != null)
{
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
try
{
stream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
try {
Bitmap bmpDefault = BitmapFactory.decodeResource(getResources(), R.drawable.na);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//bmpDefault.compress(Bitmap.CompressFormat.JPEG, 100, stream);
bmpDefault.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return byteArray;
}
控制流程不会执行 if 语句块,而是进入 else 语句块,并且 BitmapFactory.decodeFile() 总是返回 null。我错在哪里了?
imgPath
是指什么?它是有效的图像文件吗?你尝试查看它的二进制内容了吗? - pskinkdecodeFile(String pathName)
自 API level 1 开始添加 将文件路径解码为位图。如果指定的文件名为空,或无法解码为位图,则该函数返回 null。 - pskinkdecodeFile
的文档。 - pskink