Android 将位图保存到SD卡
我有一个位图图像,我必须存储在SD卡的文件夹中,我的代码如下所示。它会按预期创建文件夹和文件,但图像不会存储到文件中,它仍然是一个空文件。。。谁能告诉我怎么了Android 将位图保存到SD卡,android,bitmap,outputstream,fileoutputstream,Android,Bitmap,Outputstream,Fileoutputstream,我有一个位图图像,我必须存储在SD卡的文件夹中,我的代码如下所示。它会按预期创建文件夹和文件,但图像不会存储到文件中,它仍然是一个空文件。。。谁能告诉我怎么了 Bitmap merged = Bitmap.createBitmap(mDragLayer.getChildAt(0).getWidth(), mDragLayer.getChildAt(0).getHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(merged); /
Bitmap merged = Bitmap.createBitmap(mDragLayer.getChildAt(0).getWidth(), mDragLayer.getChildAt(0).getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(merged);
// save to folder in sd card
try {
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "folder");
if(!imagesFolder.exists())
imagesFolder.mkdirs();
int imageNum;
if(imagesFolder.list()==null)
imageNum = 1;
else
imageNum = imagesFolder.list().length + 1;
String fileName = "file_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while(output.exists()){
imageNum++;
fileName = "file_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
OutputStream fOut = new FileOutputStream(output);
merged.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
首先向AndroidManifest.xml添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
已更新
String strMyImagePath = f.getAbsolutePath();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG,70, fos);
fos.flush();
fos.close();
// MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
你只需要一个位图 您必须传递一个路径来存储图像
Bitmap b = pagesView.getDrawingCache();
b.compress(CompressFormat.JPEG, 100, new FileOutputStream(Environment.getExternalStorageDirectory() + "/NameOfFile.jpg"));
您必须在清单文件中添加权限
不要让复杂的代码变得困难。它非常简单,请尝试下面的代码
在sd卡中创建第一个目录:
public static String strpath = android.os.Environment.getExternalStorageDirectory().toString();
public static String dirName = "DIR_NAME";
File makeDirectory = new File(strpath+"/"+dirName);
makeDirectory.mkdir();
然后您应该创建两个字符串变量,如下所示:
String filename = "yourImageName".jpg";
String dirpath =strpath + "/"+dirName + "/";
使文件变为变量:
File storagePath = new File(dirpath);
File myImage = new File(storagePath, filename);
outStream = new FileOutputStream(myImage);
outStream.write(data);
outStream.close();
希望这可能对您有所帮助。我应该将实际位图放在哪里?
File storagePath = new File(dirpath);
File myImage = new File(storagePath, filename);
outStream = new FileOutputStream(myImage);
outStream.write(data);
outStream.close();