尽管存在图像,但BitmapFactory返回null

Swa*_*and 5 android bitmapfactory

在这里,我想从字符串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;

}
Run Code Online (Sandbox Code Playgroud)

控制流不执行if块,而是进入else块,并且BitmapFactory.decodeFile()始终返回null。我哪里出问题了?

Nak*_*kul 2

您可以使用此参考,它可能对您有帮助。

注意:- 此函数创建网络连接,您应该在线程或 AsyncTask 内调用它。否则可能会抛出NetworkOnMainThread异常。

由于该函数返回位图,因此您必须等待线程执行,因此请检查此问题。它使用 join()

我希望这有帮助。