我是新手,当涉及到编程android。我使用两种方式(即通过使用意图或创建文件)在活动之间传输图像,但它需要大约3或4秒才能传输图像并在第二个活动的图像视图中显示。有什么办法可以让我更快地传输,因为很多应用程序,比如whatsapp,都以更快的速度传输。我的代码如下。任何帮助,将不胜感激。在活动之间传输图像的最快方式
代码在第一个活动:
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
mCamera.stopPreview();
Intent myintent = new Intent(CameraSetter.this,CameraPhotoViewer.class);
Bitmap bitmap_image = BitmapFactory.decodeByteArray(data, 0, data.length);
String fileName = "myImage";//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap_image.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
startActivity(myintent);
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
}
};
和第二:
Bitmap bitmap_image = BitmapFactory.decodeStream(getApplicationContext().openFileInput("myImage"));
imageview.setImageBitmap(bitmap_image);
这是工作,但我想要更多更快的方式什么想法?
也尝试将图像保存到内部存储,但它也花费了太多时间。
代码:
在第一项活动:
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
mCamera.stopPreview();
Intent myintent = new Intent(CameraSetter.this, CameraPhotoViewer.class);
Bitmap bitmap_image = BitmapFactory.decodeByteArray(data, 0, data.length);
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath = new File(directory, "profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmap_image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
startActivity(myintent);
System.out.print(directory.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
,并在第二个活动:
imageview = (ImageView) findViewById(R.id.imview_camera_setter);
framelayout = (FrameLayout) findViewById(R.id.frame_layout_viewer);
try {
File f=new File(internalpath, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
imageview.setImageBitmap(Bitmap.createScaledBitmap(b, 300, 300, false));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
仍然需要太多的时间
您应该将图像保存在一个文件中,创建一个低分辨率版本作为第二个活动的预览,直到完成加载完整版本并交换为止。顺便说一下,你显示的图像不应该太大,以防止UI无响应或OOM。 – MatPag
我应该在应用程序中保存这个文件吗? @MatPag – exceptionnotgood
是的,你可以使用你的应用程序内部存储文件夹来存储原始文件,也可以使用缓存来存储我已经实现的预览 – MatPag