繁体   English   中英

如何在Android中下载图片?

[英]How to download image in android?

我在右边有一个图片,在左边有一个“下载”按钮。 图片来自我的绘画。 现在,当我尝试单击下载时,我想将图像放入我的sdcard下载中。 请帮助我,我只看到有关URL下载的信息。 还有其他解决方案吗? 谢谢

public class ImageDownloader {

public void download(String url, ImageView imageView) {
        BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
        task.execute(url);
    }
}

 /* class BitmapDownloaderTask, see below */
}

首先,您需要获取位图。 您已经可以将其作为对象位图,或者可以尝试从ImageView获取它,例如:

 BitmapDrawable drawable = (BitmapDrawable) ImageView.getDrawable();
    Bitmap bitmap = drawable.getBitmap();

然后,您必须从SD卡进入目录(文件对象),例如:

File sdCardDirectory = Environment.getExternalStorageDirectory();

接下来,创建用于存储图像的特定文件:

 File image = new File(sdCardDirectory, "test.png");

之后,您只需要编写位图,例如:

boolean success = false;

// Encode the file as a PNG image.
FileOutputStream outStream;
try {

    outStream = new FileOutputStream(image);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
    /* 100 to keep full quality of the image */

    outStream.flush();
    outStream.close();
    success = true;
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

最后,仅在需要时处理布尔结果。 如:

if (success) {
    Toast.makeText(getApplicationContext(), "Image saved with success",
            Toast.LENGTH_LONG).show();
} else {
    Toast.makeText(getApplicationContext(),
            "Error during image saving", Toast.LENGTH_LONG).show();
}

不要忘记在清单中添加以下权限:

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

暂无
暂无

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

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