如何将图像保存到SD卡上的按钮,点击机器人 [英] How to save the image to SD card on button Click android

查看:136
本文介绍了如何将图像保存到SD卡上的按钮,点击机器人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的ImageView和1 XML一个按钮,我从web服务器retriving的图像,URL和ImageView的显示出来。现在,如果按钮(保存)被点击我需要特定的图像保存到SD卡上。如何做到这一点?

I am using an Imageview and a Button in 1 XML, and I am retriving the images as URL from webServer and displaying it on the ImageView. Now if the Button(Save) is clicked I need to save that particular image into SD card. How to do this?

注:present图像应保存

NOTE: Present Image Should be saved.

推荐答案

首先,你需要得到你的位图。你已经可以把它作为一个对象位图,或者你可以尝试从ImageView的,如得到它:

First, you need to get your Bitmap. You can already have it as an object Bitmap, or you can try to get it from the ImageView such as:

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

然后,你一定要到目录(文件对象),从SD卡,如:

Then you must get to directory (a File object) from SD Card such as:

    File sdCardDirectory = Environment.getExternalStorageDirectory();

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

Next, create your specific file for image storage:

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

在此之后,你只需要编写位图得益于其方法<一href="http://developer.android.com/reference/android/graphics/Bitmap.html#com$p$pss%28android.graphics.Bitmap.Com$p$pssFormat,%20int,%20java.io.OutputStream%29">com$p$pss如:

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

最后,只是处理的布尔结果如果需要的话。如:

Finally, just deal with the boolean result if needed. Such as:

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

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

Don't forget to add the following permission in your Manifest:

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

这篇关于如何将图像保存到SD卡上的按钮,点击机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆