关于OOE这个异常本人还没找到完全解决的方法,此例子仅供大家参考
BitMap处理
I decode bitmaps from the SD card using BitmapFactory.decodeFile
. Sometimes the bitmaps are bigger than what the application needs or that the heap allows, so I useBitmapFactory.Options.inSampleSize
to request a subsampled (smaller) bitmap.
The problem is that the platform does not enforce the exact value of inSampleSize, and I sometimes end up with a bitmap either too small, or still too big for the available memory.
代码如下:
BitmapFactory.Options bounds= newBitmapFactory.Options();
this.bounds.inJustDecodeBounds= true;
BitmapFactory.decodeFile(filePath, bounds);
if(bounds.outWidth== -1){ // TODO: Error }
int width= bounds.outWidth;
int height= bounds.outHeight;
boolean withinBounds= width <= maxWidth&& height <= maxHeight;
if(!withinBounds){
int newWidth= calculateNewWidth(int width,int height);
float sampleSizeF= (float) width/ (float) newWidth;
int sampleSize= Math.round(sampleSizeF);
BitmapFactory.Options resample= newBitmapFactory.Options();
resample.inSampleSize= sampleSize;
bitmap =BitmapFactory.decodeFile(filePath, resample);
}
加载图片有两种情况:
1,//Download the Image and Display it:
Drawable DownloadDrawable(String url, String src_name) throws java.io.IOException {
return Drawable.createFromStream(((java.io.InputStream) new java.net.URL(url).getContent()), src_name);
}
[...]
try {
Drawable drw = DownloadDrawable("http://www.google.de/intl/en_com/images/srpr/logo1w.png", "src")
ImageView1.setImageDrawable(drw);
} catch (IOException e) {
// Something went wrong here
}
2,//Dowload the Image, Save it to “Hard-Disk” and load it later to Display it.
public static void DownloadFile(String imageURL, String fileName) throws IOException {
URL url = new URL(imageURL);
File file = new File(fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadFile", "Begin Download URL: " + url + " Filename: " + fileName);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
baf.append((byte) current);
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("DownloadFile", "File was downloaded in: " + ((System.currentTimeMillis() - startTime) / 1000) + "s");
}
[...]
try {
String imagePath = getFilesDir() + "/" + "logo1w.png";
DownloadFile("http://www.google.de/intl/en_com/images/srpr/logo1w.png", imagePath);
} catch (IOException e) {
// Something went wrong here
}
ImageView1.setbMap(BitmapFactory.decodeFile(imagePath));