我正在开发一款应用,其中一部分是从手机库中选择图片并将其作为字符串发布到网络API。问题在于我选择的图像并将其转换为字符串发送。这是我的代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_picker);
((Button) findViewById(R.id.buttonSelectMedia))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(photoPickerIntent, 2);
}
});
}
和我的onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] arr = baos.toByteArray();
String stringImage = Base64.encodeToString(arr, Base64.DEFAULT);
String fileName = imageReturnedIntent.getData().getLastPathSegment();
}
我正在从记忆中删除
String stringImage = Base64.encodeToString(arr, Base64.DEFAULT);
关心所有人。
答案 0 :(得分:0)
为了在处理图片时避免Android中的 Out of Memory异常,您可以使用BitmapFactory.Options
,以下是更多信息和代码Loading Large Bitmaps Efficiently。
答案 1 :(得分:0)
我找到了正在寻找的最终结果的不同路径。这是我的OnActivityResult的一部分:
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
String extension = filePath.substring(filePath.lastIndexOf(".")+1);
isBusy = true;
File file = new File(filePath);
FileInputStream mediaStream = new FileInputStream(file);
从这段代码我可以做以下事情:
mediaStream.available()
做我的工作。关心所有人并感谢他们的帮助。