从ImageView保存图像

时间:2013-06-26 17:37:45

标签: java android imageview image

我尝试将图像从ImageView保存到图库中。我试过这样的话:

Bitmap bitmap = imageView.getDrawingCache();  

MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "" , "");

但它不会起作用:/没有错误,没有:/有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

FileOutputStream fos= null;
File file = getDisc();
if(!file.exists() && !file.mkdirs()) {
    //Toast.makeText(this, "Can't create directory to store image", Toast.LENGTH_LONG).show();
    //return;
    print("file not created");
    return;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmsshhmmss");
String date = simpleDateFormat.format(new Date());
String name = "FileName"+date+".jpg";
String file_name = file.getAbsolutePath()+"/"+name;
File new_file = new File(file_name);
print("new_file created");
try {
    fos= new FileOutputStream(new_file);
    Bitmap bitmap = viewToBitmap(iv, iv.getWidth(), iv.getHeight() );
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    Toast.makeText(this, "Save success", Toast.LENGTH_LONG).show();
    fos.flush();
    fos.close();
} catch (FileNotFoundException e) {
    print("FNF");
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
refreshGallery(new_file);

助手:

public void refreshGallery(File file){
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
}

private File getDisc(){
String t= getCurrentDateAndTime();
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(file, "ImageDemo");
}

private String getCurrentDateAndTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formattedDate = df.format(c.getTime());
return formattedDate;

public static Bitmap viewToBitmap(View view, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}