[英]Android: Saving image to storage
目前,我的应用程序正在拍照,然后将数据放入ImageView中。
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
现在,我希望它执行此操作:当用户单击“保存按钮”按钮时,我希望将其保存到存储中。 我该怎么办? 我使用OnClick侦听器设置了按钮。
public void save_btn() {
}
步骤1:在某处握住Bitmap
步骤#2:单击按钮后,派生一个后台线程, AsyncTask
, IntentService
等进行工作
步骤#3:在后台线程(或其他线程)中, 在Bitmap
上调用compress()
,在要写入的任何文件上提供OutputStream
。
使用位图压缩方法将位图存储到android数据存储中。 如果要存储完整尺寸的图像,请在文件uri中使用intent.putExtra,甚至可以创建自己的内容提供程序(这是我的最爱)。
bmp.compress(Bitmap.CompressFormat.PNG,85,fOut);
http://developer.android.com/training/camera/photobasics.html#TaskPath
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
尝试这个:
String filename = "somename.jpg"; // your filename with path to sdcard
File file = new File(filename);
OutputStream outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream); // your bitmap
outStream.flush();
outStream.close();
使用该代码,您可以将图像保存在SD卡上:
FileOutputStream outStream = null;
File f=new File(Environment.getExternalStorageDirectory()+"/My Image/");
f.mkdir();
String extStorageDirectory = f.toString();
File file = new File(extStorageDirectory, "image.jpg");
pathOfImage = file.getAbsolutePath();
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
Toast.makeText(getApplicationContext(), "Saved at "+f.getAbsolutePath(), Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {e.printStackTrace();}
try {
outStream.flush();
outStream.close();
} catch (IOException e) {e.printStackTrace();}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.