如何将图像保存到SD卡上按钮单击

时间:2017-02-12 15:22:25

标签: android android-imageview

我正在使用Imageview和Button,我正在将文本转换为来自Codings的qrcode并将其显示在ImageView上。现在,如果单击按钮(保存),我需要将该特定图像保存到SD卡中。怎么做?

注意:应保存生成的图像。

以下是主要活动代码:

@Override
public class GeneratorActivity extends AppCompatActivity {
EditText text;
Button gen;
ImageView image;
String text2Qr;
static final int REQUEST_IMAGE_CAPTURE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_generator);
    text = (EditText) findViewById(R.id.text);
    gen = (Button) findViewById(R.id.gen);
    image = (ImageView) findViewById(R.id.image);
    gen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            text2Qr = text.getText().toString().trim();
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            try{
                BitMatrix bitMatrix = multiFormatWriter.encode(text2Qr, BarcodeFormat.QR_CODE,200,200);
                BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
                Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
                image.setImageBitmap(bitmap);
            }
            catch (WriterException e){
                e.printStackTrace();
            }
        }
    });

    }

}

}

这是xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_generator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.steven.qrcodegenerator.GeneratorActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="QR Code Generator"/>
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    android:hint="Enter Text to generate"
    android:id="@+id/text"/>
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="100dp"
    android:layout_centerHorizontal="true"
    android:text="GENERATE"
    android:id="@+id/gen"/>
<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_marginTop="155dp"
    android:background="@android:color/black"
    android:id="@+id/view" />
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="500dp"
    android:layout_below="@+id/view">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image"/>
</LinearLayout>

<Button
    android:text="SAVE IMAGE"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:layout_alignBaseline="@+id/gen"
    android:layout_alignBottom="@+id/gen"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginRight="19dp"
    android:layout_marginEnd="19dp" />
    </RelativeLayout>

1 个答案:

答案 0 :(得分:0)

更改SD卡中图像的代码保存。此代码在图库中创建新文件夹。

    private static String extStorageDirectory = Environment
                    .getExternalStorageDirectory().toString();
            private static String newFolder = "/YourGallery";


         gen.setOnClickListener(new View.OnClickListener() {
                @Override 
                public void onClick(View view) {

                saveImage();

                } 
            }); 

            } 

             @SuppressLint("SimpleDateFormat")
            public void saveImage() throws IOException {

                String _location;

                if (isSdPresent()) {
                    File folder = new File(extStorageDirectory + newFolder);
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                    _location = extStorageDirectory + newFolder;
                } else {
                    try {
                        File myNewFolder = new File(getFilesDir() + newFolder);
                        if (!myNewFolder.exists())
                            myNewFolder.mkdir();
                    } catch (Exception e1) {
                        Toast.makeText(getLocalContext(),
                                "Desire folder in sd card not found", Toast.LENGTH_LONG)
                                .show();
                        e1.printStackTrace();
                    }

                    _location = getFilesDir() + newFolder;
                }
                Calendar currentDate = Calendar.getInstance();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMMddHmmss");
                String dateNow = formatter.format(currentDate.getTime());
                File file = new File(_location + "/" + dateNow + ".9.JPEG");

                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(file);

                    image.setDrawingCacheEnabled(true);


                    Bitmap bitmap = Bitmap.createBitmap(image.getDrawingCache());
                    image.setDrawingCacheEnabled(false);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.close();

                    MediaScannerConnection.scanFile(this,
                            new String[]{file.toString()}, null,
                            new MediaScannerConnection.OnScanCompletedListener() {
                                public void onScanCompleted(String path, Uri uri) {
                                    Log.i("ExternalStorage", "Scanned " + path + ":");
                                    Log.i("ExternalStorage", "-> uri=" + uri);

                                  /*  Toast.makeText(getLocalContext(),"Scanned " + path + ":",Toast.LENGTH_LONG);
                                    Toast.makeText(getLocalContext(),"-> uri=" + uri,Toast.LENGTH_LONG);*/


                                }
                            });

                    Toast.makeText(getLocalContext(), "Successfully saved",
                            Toast.LENGTH_LONG).show();

                } catch (FileNotFoundException e) {
                    Toast.makeText(getLocalContext(), "Error", Toast.LENGTH_LONG)
                            .show();

                }

            }

  public static boolean isSdPresent() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }