mHomePage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE);
}
});
mHomePage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD);
}
});
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When an Image is picked
if (requestCode == RESULT_LOAD && resultCode == RESULT_OK) {
Uri resultUri = data.getData();
CropImage.activity(resultUri)
.start(getActivity());
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Uri uri = result.getUri();
Bitmap realImage = BitmapFactory.decodeStream(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
edit.commit();
}
试图通过编码将图像存储在sharedpreference中,但是我对此并不陌生,无法弄清楚。我看到了一些与此问题有关的问题,但不清楚。有人可以帮我解决如何在SharedPreferences
中存储路径/图像吗?
由于我将uri放入.decodeStream()
的inout流中,所以代码甚至都没有编译。
答案 0 :(得分:1)
Uri指向存储图像的路径,因此首先您必须使用InputStream
读取它。
此代码将修复编译错误。作为副节点,请使用edit.apply()
而不是edit.commit()
。
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
try
{
InputStream ims = getContentResolver().openInputStream(uri);
Bitmap realImage = BitmapFactory.decodeStream(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
//edit.commit();
edit.apply();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
但是,在SharedPreferences中存储图像真的没有意义吗?这并不是真的。您为什么不使用将文件保存在context.getFilesDir()
中并在需要时从那里读取文件?比编码/解码要好。