Universalimageloader 原圖片大小獲取
阿新 • • 發佈:2019-02-06
Universalimageloader1.9.5上還沒有對外提供獲取圖片的原大小功能,如果需要獲取圖片的源大小,可參考stackoverflow上的解決辦法
stackoverflow地址
主要實現步驟如下:
1、自定義ImageDecoder
ImageDecoder不需要自己去實現,直接把專案自帶的BaseImageDecoder上的程式碼拷出來即可。
2、定義map存放圖片對應的原圖大小資訊
//存放源圖片大小資料
protected static final Map<String, ImageSize> sizeMap = Collections.synchronizedMap(new HashMap<String, ImageSize>());
3、在decoder獲取到圖片大小以及圖片資訊後,將原圖片大小資訊儲存起來。
public Bitmap decode(ImageDecodingInfo decodingInfo) throws IOException {
Bitmap decodedBitmap;
ImageFileInfo imageInfo;
InputStream imageStream = getImageStream(decodingInfo);
if (imageStream == null ) {
L.e(ERROR_NO_IMAGE_STREAM, decodingInfo.getImageKey());
return null;
}
try {
imageInfo = defineImageSizeAndRotation(imageStream, decodingInfo);
//儲存原圖片大小資訊
sizeMap.put(decodingInfo.getOriginalImageUri(), imageInfo.imageSize);
imageStream = resetStream(imageStream, decodingInfo);
Options decodingOptions = prepareDecodingOptions(imageInfo.imageSize, decodingInfo);
decodedBitmap = BitmapFactory.decodeStream(imageStream, null , decodingOptions);
} finally {
IoUtils.closeSilently(imageStream);
}
if (decodedBitmap == null) {
L.e(ERROR_CANT_DECODE_IMAGE, decodingInfo.getImageKey());
} else {
decodedBitmap = considerExactScaleAndOrientatiton(decodedBitmap, decodingInfo, imageInfo.exif.rotation,
orizontal);
}
return decodedtmap;
4、提供公開api給外部呼叫
public static ImageSize getOriginSize(String url) {
return sizeMap.get(url);
}
5、只需要在需要的地方獲取原圖大小就可以了,比如在圖片顯示前或圖片載入完成後獲取原大小進行操作
builder.preProcessor(new BitmapProcessor() {
@Override
public Bitmap process(Bitmap bitmap) {
ImageSize imageSize = BaseImageDecoder.getOriginSize(imageurl);
if (null != imageSize) {
//xxxx
} else {
//xxxxxxx
}
return bitmap;
}
});