无法压缩某些远程图像

时间:2010-11-16 16:28:30

标签: android

我有一个方法可以缓存来自远程URL的图像并返回缓存的图像。如果图像已经被缓存,则只返回它 - 否则它将转到远程URL并将位图压缩到缓存。

我的问题是有些照片(从Flickr的网络服务获取),从未成功compress,并且从未通过BitmapFactory.decodeStream(inputStream)成功解码

这是我的缓存方法:

public static Bitmap createImage(Context context, String imageUrl, String imageName) {
        Bitmap image = null;
        try {
            if(new File(context.getCacheDir(), imageName).exists())
                return BitmapFactory.decodeFile(new File(context.getCacheDir(), imageName).getPath());

            //load file from web
            image = BitmapFactory.decodeStream(HttpClient.fetchInputStream(imageUrl));

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(new File(context.getCacheDir(), imageName));
            }

            //this should never happen
            catch(FileNotFoundException e) {
                if(Constants.LOGGING)
                    Log.e(TAG, e.toString(), e);
            }

            //if the file couldn't be saved
            if(fos != null && image != null) {
                if(!image.compress(Constants.BITMAP_CACHE_COMPRESS_FORMAT, Constants.CACHE_IMAGE_QUALITY, fos)) {
                    if(Constants.LOGGING)
                        Log.e(TAG, "The image could not be saved: " + imageName + " - " + imageUrl);
                    image = BitmapFactory.decodeResource(context.getResources(), R.drawable.twitter_default_icon);
                }
                fos.flush();
                fos.close();
            }
            else
                image = BitmapFactory.decodeResource(context.getResources(), R.drawable.twitter_default_icon);
        }
        catch(IOException e) {
            if(Constants.LOGGING)
                Log.e(TAG, e.toString(), e);
        }
        return image;
    }

image.compress无法成功保存位图的原因是什么?

BitmapFactory.decoodeStream无法正确创建位图的原因是什么?

它似乎只是一些图像(有时图像无法加载,成功加载),这是令人困惑的。

以下是我获取远程图像InputStream的方法:

protected static InputStream fetchInputStream(String url) {
        try {
            return new URL(url.replace(" ", "%20")).openStream();
        }
        catch(MalformedURLException e) {
            if(Constants.LOGGING)
                Log.e(TAG, e.toString());
        }
        catch(IOException e) {
            if(Constants.LOGGING)
                Log.e(TAG, e.toString());
        }
        return null;
    }

编辑:我似乎没有在G1上遇到麻烦(90%的时间),但在三星Galaxy-s上我有很多问题显示很多图像

编辑我的编辑,erg:一些图像集在g1和galaxy-s上完美运行,而一些图像集大多只能在g1上运行。呃废话是怎么回事?

0 个答案:

没有答案