如何从图库中获取图像,将其裁剪并保存在应用程序中

How to get a image from gallery, crop it and save it in app

在我的项目中,我使用圆形图像视图来显示我从 phone 的画廊获得的图像,然后将图像设置为图像视图 - 到这里一切正常.

但问题是当我从一个片段交易到另一个片段时图像被删除。

所以我需要一个代码片段来帮助我从图库中挑选图像并裁剪它,然后在图像视图中永久显示该图像。

PS: 此图像也已上传到 Fire Base 存储。所以帮我解决这个问题

用于图像提取

@Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE && resultCode == RESULT_OK){

            Uri imageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
                profileImage.setImageBitmap(bitmap);

            }catch (IOException e){
                Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT).show();
            }
        }
    }

图片选择

profileImage = view.findViewById(R.id.profile_image);
        profileImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent gallery = new Intent();
                gallery.setType("image/*");
                gallery.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(gallery,"Select Profile Image"), PICK_IMAGE);
            }
        });

Buy me a coffee

我建议你使用这个。它是图像裁剪器 https://github.com/ArthurHub/Android-Image-Cropper

为了将位图结果保存到 sharedPrf 你应该将位图转换为 base64 对于上传,您应该将其转换为文件

文件示例

File f = new File(context.getCacheDir(), filename);
f.createNewFile();

//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();

对于 base64:

 ByteArrayOutputStream baos = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

byte[] imageBytes = baos.toByteArray();

String base64String = Base64.encodeToString(imageBytes, Base64.NO_WRAP);

要将 base64 字符串解码回位图图像:

byte[] decodedByteArray = Base64.decode(base64String, Base64.NO_WRAP);
Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedByteArray, 0, decodedString.length);