1

我正在尝试将捕获的图像存储到我的存储中,但出现错误:

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

}

4

1 回答 1

1

将此添加到您的清单中

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

您没有访问存储的权限这里是开发指南的链接 https://developer.android.com/guide/topics/permissions/overview

于 2020-11-25T07:42:19.503 回答