android - 尽管存在图像,BitmapFactory 返回 null

标签 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;

}

控制流不执行 if block ,而是进入 else block ,BitmapFactory.decodeFile() 始终返回 null。我哪里错了?

最佳答案

Ravindra 的 的回答很有帮助,为了更好地利用图像,请尝试 Picasso lib,这令人兴奋。它还具有调整大小/裁剪方法。

Picasso.with(getContext()).load("your url").into(new Target() {
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                        //do what ever you want with your bitmap 
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {

                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {

                    }
                });

关于android - 尽管存在图像,BitmapFactory 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34306087/

相关文章:

android - BitmapFactory.decodeResource 和莫名其妙的Out of Memory

android - 如何设置自定义切换按钮android的文本

android - java.lang.OutOfMemoryError 在 android.graphics.BitmapFactory.decodeResource (BitmapFactory.java :374)

Android 颜色格式(RGB565、ARGB8888)

java - BitmapFactory.decodeFile 返回 null

android - 在 0x09050941(代码=1)处获取错误致命信号 11(SIGSEGV)关于使用 Canvas 制作圆形图像

php - 我的在线测验 Android 应用程序的良好数据库设计方法是什么?

android - 代号一 : receive sms on Android by native code

android - 在使用 Camera API Android 拍摄的图像上添加当前时间戳

android - 谷歌地图 API 中的 "Google Play services are updating"