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

6za6bjd0  于 2023-02-13  发布在  Android
关注(0)|答案(1)|浏览(227)

在我的项目中,我使用一个圆形的图像视图来显示我从手机的图库中获得的图像,然后将该图像设置为图像视图到目前为止,一切工作正常。
但问题是,当我从一个片段到另一个片段进行处理时,图像会被删除。
因此,我需要一个代码片段,帮助我从画廊挑选一个图像和裁剪它,然后永远显示在图像视图中的图像。
PS:这张图片也被上传到了消防基地的存储器里。所以请帮助我如何解决这个问题
用于图像提取

@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);
            }
        });
bcs8qyzn

bcs8qyzn1#

我建议你用这个。它是图像裁剪器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);

相关问题