[英]android: save images to specific folder in the sd card
我在這里有一個代碼段,可在SD卡上保存位圖:
String filename = String.valueOf(System.currentTimeMillis()) ;
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, filename);
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
try {
OutputStream outStream = getContentResolver().openOutputStream(uri);
bm.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
outStream.flush();
outStream.close();
默認存儲為圖庫中的“ Camera”文件夾。
我的問題是:
使用上面的代碼,我可以將圖像保存到SD卡上的其他文件夾中嗎?
嘗試這個
File myDir=new File("/sdcard/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
並在清單中添加
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在這里檢查我的答案: https : //stackoverflow.com/a/7887114/964741
請嘗試以下代碼,
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath());
dir.mkdirs();
File out = new File(dir,filename);
try {
out.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DataOutputStream fo = null;
try {
fo = new DataOutputStream( new FileOutputStream(out));
//write what you want to fo
fo.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
請嘗試以下代碼。
URL imageUrl = new URL("url");
Bitmap bitmap=BitmapFactory.decodeStream(imageURLFacebook.openConnection().getInputStream());
saveToInternalStorage(bitmap);//call method and pass bitmap
保存在內部存儲器中的方法
private String saveToInternalStorage(Bitmap bitmapImage) {
File directory = Environment.getExternalStorageDirectory();
File childDirectory = new File(directory, "FolderName");
if (!childDirectory.exists()) {
childDirectory.mkdirs();
}
// Create imageDir
File mypath = new File(childDirectory, "profile.jpeg");
try {
FileOutputStream fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return String.valueOf(mypath);
}
在清單中添加
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.