Android studio 如何从gallery中获取图像、裁剪图像并将其保存在应用程序中
在我的项目中,我使用圆形图像视图来显示我从手机多媒体资料中获取的图像,然后将图像设置为图像视图,直到这里一切正常 但问题是,当我从一个片段处理到另一个片段时,图像会被删除 因此,我需要一个代码片段,它可以帮助我从图库中选择一个图像并进行裁剪,然后在图像视图中永远显示该图像 PS:此图像也已上载到Fire Base存储。那帮我怎么解决这个问题呢 用于图像提取Android studio 如何从gallery中获取图像、裁剪图像并将其保存在应用程序中,android-studio,sharedpreferences,android-imageview,Android Studio,Sharedpreferences,Android Imageview,在我的项目中,我使用圆形图像视图来显示我从手机多媒体资料中获取的图像,然后将图像设置为图像视图,直到这里一切正常 但问题是,当我从一个片段处理到另一个片段时,图像会被删除 因此,我需要一个代码片段,它可以帮助我从图库中选择一个图像并进行裁剪,然后在图像视图中永远显示该图像 PS:此图像也已上载到Fire Base存储。那帮我怎么解决这个问题呢 用于图像提取 @Override public void onActivityResult(int requestCode, int result
@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);
}
});
我建议你用这个。这是图像裁剪器
要将位图结果保存到SharedPF,应将位图转换为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后,我必须将字符串传递到SharedReferences权限才能再次使用它我必须使用if语句来恢复正确的内容。您是否也能帮我回答这个问题