【问题标题】:Take a photo, save it in app drawables and display it in an ImageButton拍照,将其保存在应用程序可绘制对象中并在 ImageButton 中显示
【发布时间】:2012-11-20 22:46:05
【问题描述】:
我有一个带有 ImageButton 的 Android 应用。当用户点击它时,意图启动以显示相机活动。当用户捕获图像时,我想将其保存在应用程序的可绘制文件夹中,并将其显示在用户单击的同一个 ImageButton 中,替换以前的可绘制图像。我使用了这里发布的活动:Capture Image from Camera and Display in Activity
...但是当我捕获图像时,活动不会返回到包含 ImageButton 的活动。
编辑代码为:
public void manage_shop()
{
static final int CAMERA_REQUEST = 1888;
[...]
ImageView photo = (ImageView)findViewById(R.id.getimg);
photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, CAMERA_REQUEST);
}
});
[...]
}
和 onActivityResult():
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
ImageButton getimage = (ImageButton)findViewById(R.id.getimg);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
{
Bitmap getphoto = (Bitmap) data.getExtras().get("data");
getimage.setImageBitmap(getphoto);
}
}
如何将捕获的图像也存储在可绘制文件夹中?
【问题讨论】:
标签:
android
android-activity
camera
【解决方案1】:
将图像保存到文件后,您可以使用以下 sn-p 添加到图库。
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, new File(path).toString());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATA, path);
getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI , values);
要将文件保存到目录,请执行以下操作
private saveFileToDir() {
final InputStream in = Wherever you input stream comes from;
File f = generatePhotoFile();
OutputStream out = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int len;
while ((len=in.read(buffer))>0)
{
out.write(buffer,0,len);
}
in.close();
out.flush();
out.close();
}
private File generatePhotoFile() throws IOException {
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyymmdd_hhmmss");
String newPicFile = "IMG_"+ df.format(date) + ".jpg";
File f = new File(Environment.getExternalStorageDirectory()+"/DCIM/Camera/", newPicFile);
if (!f.exists())
{
if(!f.getParentFile().exists())
f.getParentFile().mkdir();
f.createNewFile();
}
return f;
}