我想在我的活动中返回一个位图,以便其他应用程序可以使用它.
返回文本很清楚.
- Intent data = new Intent();
- data.putExtra("text1","text.");
- data.putExtra("text2","longer text.");
- setResult(RESULT_OK,data);
但是如何返回位图?
更多信息:
该活动有几个意图可供想要获取图像的每个人使用.
- <intent-filter>
- <action android:name="android.intent.action.GET_CONTENT" />
- <category android:name="android.intent.category.OPENABLE" />
- <category android:name="android.intent.category.DEFAULT" />
- <data android:mimeType="image/*" />
- <data android:mimeType="vnd.android.cursor.dir/image" />
- </intent-filter>
- <intent-filter>
- <action android:name="android.intent.action.PICK" />
- <category android:name="android.intent.category.DEFAULT" />
- <data android:mimeType="image/*" />
- <data android:mimeType="vnd.android.cursor.dir/image" />
- </intent-filter>
- public void finish(Bitmap bitmap) {
- try {
- File folder = new File(Environment.getExternalStorageDirectory() + "/Icon Select/");
- if(!folder.exists()) {
- folder.mkdirs();
- }
- File nomediaFile = new File(folder,".nomedia");
- if(!nomediaFile.exists()) {
- nomediaFile.createNewFile();
- }
- FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Icon Select/latest.png");
- bitmap.compress(Bitmap.CompressFormat.PNG,90,out);
- File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/Icon Select/latest.png");
- if(bitmapFile.exists()) {
- Intent localIntent = new Intent().setData(Uri.fromFile(bitmapFile));
- setResult(RESULT_OK,localIntent);
- } else {
- setResult(RESULT_CANCELED);
- }
- super.finish();
- } catch (Exception e) {
- e.printStackTrace();
- Log.d("beewhale","Error writing data");
- }
- }
解决方法
虽然我同意Ovidiu Latcu,但您可能会遇到内存问题.
将位图存储到SD卡上的临时位置可能更好.然后从那里访问它. (写入和读取位图到文件).
或者,如果您确实希望将字节数组作为额外内容,则首先将位图压缩为另一种格式,例如Jpeg或类似的,这将再次减少内存问题的变化.
一个简单的8M像素图像,是32MB(4层).这超出了应用程序大多数(如果不是全部)手机的允许内存使用量.
直接存储到存储是内置相机应用程序如何工作以避免此问题.
这是我处理它的代码:
- public void showCameraScreen(View view) {
- // BUILT IN CAMERA
- Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- camera.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(getTempFile(this)) );
- this.startActivityForResult(camera,1);
- }
- private File getTempFile(Context context) {
- // it will return /sdcard/MyImage.tmp
- final File path = new File(Environment.getExternalStorageDirectory(),context.getPackageName());
- if (!path.exists()) {
- path.mkdir();
- }
- return new File(path,"MyImage.tmp");
- }
- @Override
- protected void onActivityResult(int requestCode,int resultCode,Intent data) {
- if (requestCode == 1 && resultCode == RESULT_OK) {
- final File file = getTempFile(this);
- byte[] _data = new byte[(int) file.length()];
- try {
- InputStream in = new FileInputStream(file);
- in.read(_data);
- in.close();
- in = null;
- //DO WHAT YOU WANT WITH _data. The byte array of your image.
- } catch (Exception E) {
- }
- }
- }