【问题标题】:How to get a image from gallery, crop it and save it in app如何从图库中获取图像,裁剪并保存在应用程序中
【发布时间】:2020-01-14 13:51:37
【问题描述】:

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

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

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

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】:

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

    【讨论】:

    • 谢谢,如何将其保存在服务器或共享首选项中
    • 感谢您的帮助,现在让我澄清一下。编码成 base64 后,我必须将字符串传递给 sharedpreferences 权限才能再次使用它,我必须使用 if 语句来恢复正确的内容。
    • 你也帮我回答这个问题吗stackoverflow.com/questions/59686659/…
    猜你喜欢
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多