如何在 viewpager 中旋转图像并将位图保存在现有路径上?

How to rotate image in viewpager and save bitmap on existing path?

我正在开发画廊类应用程序。

这里,我使用view pager来显示存储在内存中的图像,并且我有五个底部导航菜单。

现在我要做的是在旋转菜单上单击旋转图像并将旋转后的位图保存到现有路径。

我已经搜索了很多但没有运气。

在菜单上点击:

new AsyncTask<Void,Void,Void>(){

    @Override
    protected Void doInBackground(Void... params) {
        try {
            Bitmap myBitmap = BitmapFactory.decodeFile(Constant.image_paths.get(viewPager.getCurrentItem()));
            Bitmap newBit = rotate(myBitmap,45);
            saveToInternalStorage(newBit,Constant.image_paths.get(viewPager.getCurrentItem()));
        } catch (Exception e){
            Log.d("error","error in rotate");
        }
        return null;
   }

   @Override
   protected void onPostExecute(Void aVoid) {
       super.onPostExecute(aVoid);
       myViewPagerAdapter.notifyDataSetChanged();
   }

}.execute();




public static Bitmap rotate(Bitmap source, float angle) {
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    return Bitmap.createBitmap(source, 0, 0, source.getWidth(),source.getHeight(), matrix, false);
}
private String saveToInternalStorage(Bitmap bitmapImage,String path) throws IOException {
    ContextWrapper cw = new ContextWrapper(getActivity());
    // path to /data/data/yourapp/app_data/imageDir
 //   File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    // Create imageDir
    File mypath = new File(path);

    if(mypath.exists()){
        mypath.delete();
    }

    if(!mypath.exists()){
        mypath.createNewFile();
    }
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(mypath);
        // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return mypath.getAbsolutePath();
}    

您无法仅通过此代码实现此目的,要实现此目的,您需要执行以下步骤:

  1. 将图像转换为您从内部存储访问的位图。
  2. 将该位图传递给您在上面发布的方法 "rotate()"。
  3. Rotate 方法将 return 一个新的位图,通过 "FileOutputStream" 将该位图保存在您第一次获取图像的路径上的存储中。

如果您不知道如何保存图像,请检查此link:

Saving and Reading Bitmaps/Images from Internal memory in Android