繁体   English   中英

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

[英]How to compress an Bitmap and then save it to sd

我想从网址列表中下载一些图片。这是我的方法:

    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?

尝试这个

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();
}

并在清单中添加

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM