我有一个方法,可以从远程URL缓存图像并返回缓存的图像。如果图像已经被缓存,它只会被返回-否则它会转到远程URL并将位图压缩到缓存中。
我的问题是有些照片(从Flickr的web服务中获取)从未成功
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上工作。呃,怎么回事?