我是新手,當涉及到編程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