如何压缩位图,然后将其保存为sd



我想从url列表中下载一些图片。我是这样做的:

    public void setLocalPhotosUrl() throws IOException {

    int size;
    if(attachments.size()<3)
        size=attachments.size();
    else
        size=3;
    for(int i=0;i<size;++i){
        String filename =title.replace(" ","")+i+".jpg";
        File destination = new File(Corale.getPhotos(),filename);
        URL photoUrl = new URL(attachments.get(i).getUrl());
        InputStream is = photoUrl.openStream();
        OutputStream os = new FileOutputStream(destination);

        byte[] b = new byte[2048];
        int length;
        while ((length = is.read(b)) != -1) {
            os.write(b, 0, length);
        }
        is.close();
        os.close();
        if(checkIfValid(destination))                                   
            localPhotosUrl.add(destination.getAbsolutePath());
        else
            i--;
    }
}

但是原来有很多图片,占用的空间达到270MB,我怎么压缩图像然后保存到手机sd?

try this

String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");    
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete (); 
try {
       FileOutputStream out = new FileOutputStream(file);
       finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
       out.flush();
       out.close();
} catch (Exception e) {
       e.printStackTrace();
}

并将其添加到manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

最新更新