如何从图库中获取图像,裁剪并保存到应用中

问题描述 投票:0回答:1

在我的项目中,我使用圆形图像视图来显示从手机图库中获取的图像,然后将图像设置为图像视图,直到此处一切正常。

但是问题是当我从一个片段到另一个片段进行处理时,图像被删除了。

所以我需要一个代码段,该代码段可帮助我从图库中拾取图像并进行裁剪,然后将其永久显示在图像视图中。

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);
            }
        });
android-studio sharedpreferences android-imageview
1个回答
0
投票

我建议您使用此。这是图像裁剪器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);
© www.soinside.com 2019 - 2024. All rights reserved.