2013-06-26 63 views
0

我試圖將圖像從ImageView保存到圖庫中。我試過這樣:從ImageView中保存圖像

Bitmap bitmap = imageView.getDrawingCache(); 

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

但它不會工作:/沒有錯,沒有:/有人可以幫助我嗎?

+0

這裏有一個很好的樣本http://stackoverflow.com/questions/9078715/how-to-save-a-bitmap- image-with-imageview-onclick – 2013-06-26 17:50:23

+0

嗯,它只是將其保存到SD卡,不是我可以看到它在畫廊和文件已創建,但您無法查看圖片:/ – Phil

+0

檢查[this](http: //stackoverflow.com/questions/19462213/android-save-images-to-internal-storage/38904356#38904356)。我已經給出瞭解決方案。希望這可以幫助! –

回答

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