如何在图库中保存图像?

时间:2016-04-14 05:39:12

标签: android image

我无法在任何地方看到图像。 没有编译错误或运行时错误 我正在使用Picasso来获取图像。

public class DownloadImage extends Activity {

ImageView imageView;
private Button saveBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.mindmaps);

    imageView = (ImageView) findViewById(R.id.imageView);
    saveBtn = (Button) findViewById(R.id.save);
    final Bitmap bm = BitmapFactory.decodeResource(getResources(), R.id.imageView);
    saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            savePicture(bm, "image_name.jpg");
            Toast.makeText(getApplicationContext(), "Image saved...", Toast.LENGTH_SHORT).show();
        }
    });



 Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
}


private void savePicture(Bitmap bm, String imgName)
{
    OutputStream fOut = null;
    String strDirectory = Environment.getExternalStorageDirectory().toString();

    File dir = new File(strDirectory, imgName);
    dir.mkdir();
    try {
        fOut = new FileOutputStream(dir);

        /**Compress image**/
        bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
        fOut.flush();
        fOut.close();

        /**  Update image to gallery  **/
        MediaStore.Images.Media.insertImage(getContentResolver(),
                dir.getAbsolutePath(), dir.getName(), dir.getName());
    } catch (Exception e) {
        e.printStackTrace(); //exception
    }
  }
}

请检查是否有任何逻辑错误。 我只需要将图像视图中的图像保存到图库中。

2 个答案:

答案 0 :(得分:0)

试试这个......

 private void savePicture(Bitmap bm, String imgName)
    {
        FileOutputStream fOut = null;
        String strDirectory = Environment.getExternalStorageDirectory().toString();

        File dir = new File(strDirectory, imgName);
        dir.mkdir();
        try {
            dir.createNewFile();
            fOut = new FileOutputStream(dir);

            /**Compress image**/
            bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);



            /**Update image to gallery**/
            MediaStore.Images.Media.insertImage(getContentResolver(),
                    dir.getAbsolutePath(), dir.getName(), dir.getName());
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

答案 1 :(得分:0)

您应该使用image而不是imageView来解码位图,如下面的代码。

`final Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);