我必须将Android项目结构的drawable文件夹中的png文件保存到外部SD卡。我试过这样做,但图像没有保存。 能帮助我吗?我是android开发的新手。
PS:是的,图片在drawable文件夹中。
package com.example.vishal.demo;
import android.Manifest;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.img);
File path = Environment.getExternalStorageDirectory();
File dir = new File(path + "AndroidImageFolder/");
dir.mkdir();
File imageFileInSD = new File(dir + "OCRImage.png");
FileOutputStream out = null;
try {
out = new FileOutputStream(imageFileInSD + "");
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
确保您已向清单文件添加了正确的权限,或者使用了正在检查的v6.0方法或保存时显示权限
答案 1 :(得分:0)
试试这段代码,
File path = Environment.getExternalStorageDirectory();
File dir = new File(path + "/AndroidImageFolder/");
dir.mkdir();
在清单
中添加了权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
答案 2 :(得分:0)
试试此代码
private void SaveImage(Bitmap finalBitmap){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/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();
}
}