【发布时间】:2017-05-26 13:12:35
【问题描述】:
我是 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 我已经实现了,但它也花了很多时间。如果你愿意,我可以显示代码
-
是的,将代码添加到问题中
标签: android android-intent android-activity android-bitmap