Android:位图保存为黑色图片

时间:2016-03-06 22:09:34

标签: java android android-studio bitmap drawable

我需要将Drawable保存到文件中,然后根据需要加载。问题是从函数生成的位图一旦保存就会变成黑色图片。任何人都可以帮助我吗?我已经查看了几个类似的问题,但没有提供的答案与我的问题有关。

转换和文件功能:

public static Bitmap drawableToBitmap(Drawable d) {return Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);}

public static boolean saveDrawableToFile(File dir, String fileName, Drawable d, Bitmap.CompressFormat format, int quality) {
    return saveBitmapToFile(dir, fileName, drawableToBitmap(d), format, quality);
}

public static boolean saveBitmapToFile(File dir, String fileName, Bitmap bm, Bitmap.CompressFormat format, int quality) {

    File imageFile = new File(dir,fileName);

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(imageFile);
        bm.compress(format,quality,fos);
        fos.close();
        return true;
    }
    catch (IOException e) {
        Log.e("FileSaver",e.getMessage());
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    return false;
}

活动代码:

File file = new File(getActivity().getCacheDir(),picture.getSamplePath());


        if(file.exists()){
            //Loads local file
            Log.d(LOG_TAG, "Loading thumbnail " + file.getAbsolutePath());
            image = Drawable.createFromPath(file.getAbsolutePath());
        }else{
            //Loads url
            Log.d(LOG_TAG, "Downloading thumbnail " + urls[0]);
            image = QBooruUtils.loadDrawableFromUrl(urls[0]);

            //Saves drawable
            Log.d(LOG_TAG, "Saving thumbnail " + file.getAbsolutePath());
            QBooruUtils.saveDrawableToFile(getActivity().getCacheDir(),picture.getSamplePath(),image, Bitmap.CompressFormat.JPEG,100);
        }

loadDrawableFromUrl只是一个旨在从远程图片下载drawable的函数,它正确返回一个有效的Drawable。

记录:

03-06 21:38:04.908 9418-9751/fr.fusoft.qbooru D/PicViewerFrag: Downloading thumbnail http://konachan.com/sample/6e27694cff3910adb4e2e0f1f0fe96dc/Konachan.com%20-%20216418%20sample.jpg
03-06 21:38:05.072 9418-9464/fr.fusoft.qbooru D/OpenGLRenderer: endAllStagingAnimators on 0xb7563a60 (GridView) with handle 0xb767d510
03-06 21:38:05.083 9418-9418/fr.fusoft.qbooru I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3ab4504c time:340520855
03-06 21:38:06.147 9418-9751/fr.fusoft.qbooru D/PicViewerFrag: Saving thumbnail /data/data/fr.fusoft.qbooru/cache/Konachan_216418.jpg
03-06 21:38:08.900 9418-9868/fr.fusoft.qbooru D/PicViewerFrag: Loading thumbnail /data/data/fr.fusoft.qbooru/cache/Konachan_216418.jpg

1 个答案:

答案 0 :(得分:1)

你的函数drawableToBitmap()实际上并没有将drawable绘制成位图。它只是创建一个空白位图,其内在大小与drawable相同。

您需要使用一些实际上converts the drawable to a bitmap的代码来填充它。