我正在尝试将捕获的图像存储到我的存储中,但出现错误:
- E/GREC:/storage/emulated/0/screenshotdemo.jpg(权限被拒绝)
- java.io.FileNotFoundException:/storage/emulated/0/screenshotdemo.jpg(权限被拒绝)
我的代码如下: MainActivity.Java
public class MainActivity extends AppCompatActivity {
private ScrollView scrollView;
private Button btn;
public static Bitmap bitScroll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrollView = findViewById(R.id.scroll);
btn = findViewById(R.id.takeScreenshot);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bitScroll = getBitmapFromView(scrollView, scrollView.getChildAt(0).getHeight(), scrollView.getChildAt(0).getWidth());
saveBitmap(bitScroll);
Intent intent = new Intent(MainActivity.this, PreviewActivity.class);
startActivity(intent);
}
});
}
//create bitmap from the ScrollView
private Bitmap getBitmapFromView(View view, int height, int width) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return bitmap;
}
public void saveBitmap(Bitmap bitmap) {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
String mPath = Environment.getExternalStorageDirectory() + "/" + "screenshotdemo.jpg";
File imagePath = new File(mPath);
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Toast.makeText(getApplicationContext(), imagePath.getAbsolutePath() + "", Toast.LENGTH_LONG).show();
Log.e("ImageSave", "Saveimage");
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
}