将图像(使用 Camera Intent 拍摄)从 ImageView 保存到设备 (Gallery/SdCard)
Save Image (took with Camera Intent) from ImageView to device (Gallery/SdCard)
我制作了一个小应用程序,允许有意地打开相机并拍照。之后我在 imageView 中显示该图片。我的问题是,我想保存我拍摄的图像,该图像当前可在 imageview 上使用。如何将拍摄的图像保存到我的图库中并在图像视图中可用?我当前的代码是:
public class activity_auto extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto);
Button btnCamera= (Button)findViewById(R.id.btnCamera);
imageView=(ImageView)findViewById(R.id.imageView);
}
public void onButtonClicked(View v){
if(v.getId()==R.id.btnCamera) {
//starting camera function
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
if(v.getId()==R.id.goToGPS) {
Intent intent2 = new Intent(activity_auto.this, function_gps.class );
startActivity(intent2);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//initialize my imageview
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
imageView.setImageBitmap(bitmap);
}
}
错误日志:
06-30 11:37:25.759 2624-3776/? E/EGL_emulation: eglQueryContext 32c0 EGL_BAD_ATTRIBUTE
06-30 11:37:25.762 2624-3776/? E/EGL_emulation: tid 3776: eglQueryContext(1716): error 0x3004 (EGL_BAD_ATTRIBUTE)
06-30 11:37:26.600 1613-1624/? E/RecoverySystemService: Timed out connecting to uncrypt socket
06-30 11:37:26.600 1613-1624/? E/RecoverySystemService: Failed to connect to uncrypt socket
06-30 11:37:26.665 2412-3061/? E/SystemUpdateService: Failed to call RecoverySystem.cancelScheduledUpdate
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at xae.c(:com.google.android.gms:134)
at afuw.d(:com.google.android.gms:195)
at afuw.p(:com.google.android.gms:2178)
at afuw.a(:com.google.android.gms:448)
at afuw.doInBackground(:com.google.android.gms:50475)
at android.os.AsyncTask.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.io.IOException: cancel scheduled update failed
at android.os.RecoverySystem.cancelScheduledUpdate(RecoverySystem.java:555)
at java.lang.reflect.Method.invoke(Native Method)
at xae.c(:com.google.android.gms:134)
at afuw.d(:com.google.android.gms:195)
at afuw.p(:com.google.android.gms:2178)
at afuw.a(:com.google.android.gms:448)
at afuw.doInBackground(:com.google.android.gms:50475)
at android.os.AsyncTask.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.lang.Thread.run(Thread.java:761)
06-30 11:37:26.666 2412-3061/? E/SystemUpdateTask: exception trying to cancel scheduled update
java.io.IOException: Failed to invoke RecoverySystem.cancelScheduledUpdate
at xae.c(:com.google.android.gms:140)
at afuw.d(:com.google.android.gms:195)
at afuw.p(:com.google.android.gms:2178)
at afuw.a(:com.google.android.gms:448)
at afuw.doInBackground(:com.google.android.gms:50475)
at android.os.AsyncTask.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.lang.Thread.run(Thread.java:761)
06-30 11:37:33.447 3100-3100/com.group6.travlhoe E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.group6.travlhoe, PID: 3100
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.group6.travlhoe/com.group6.travlhoe.activity_auto}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at com.group6.travlhoe.activity_auto.onActivityResult(activity_auto.java:105)
at android.app.Activity.dispatchActivityResult(Activity.java:6915)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
06-30 11:37:40.070 3243-3264/? E/AppDataSearchHelper: Couldn't find corpus 'playlists'
编写此代码以保存图像
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG,90,bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try{
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
imageView.setImageBitmap(thumbnail);
imageView.setDrawingCacheEnabled(true);
Bitmap b = imageView.getDrawingCache();
MediaStore.Images.Media.insertImage(getContentResolver(),b,"Pics","Task5");
Toast.makeText(getApplicationContext(),"Image Saved",Toast.LENGTH_LONG).show();
}
在Manifest.xml
中写入此权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
转到设置 -> 应用程序 -> "Your App" -> 权限。允许访问相机和存储空间。
嗯,你有很多事情要做。
您需要清单和运行时中的存储权限,这本身就是一个主题。
您将需要处理外部存储以获取和使用文件夹来写入照片,并使用 ContentResolver 将照片从相机存储的位置复制到您应用程序的文件夹中。
如果您想在图库中查看照片,您还需要使用 MediaScannerConnection,以便对其进行编目并快速显示给用户。
我建议您按照一些教程进行操作。
从 Commonsware 中搜索 CWAC Cammera。他们在 Github 中有一个项目,您可以查看,如果您 google 多一点,您应该找到一个教程来解释该项目过程的每个步骤。
伙计们,我找到了将带有相机意图的照片添加到您的图库中的最佳方法:
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class activity_auto extends AppCompatActivity {
private BottomNavigationView bottomNavigationView;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto);
ImageButton btnCamera= (ImageButton)findViewById(R.id.btnCamera);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
}
public void onButtonClicked(View v){
if(v.getId()==R.id.btnCamera) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureName= getPictureName();
File imageFile= new File(pictureDirectory,pictureName);
//URI weil putExtra sonst nicht mit File elementen klar kommt!
Uri pictureUri = Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
startActivityForResult(intent, 0);
}
if(v.getId()==R.id.goToGPS) {
Intent intent2 = new Intent(activity_auto.this, function_gps.class );
startActivity(intent2);
}
}
private String getPictureName() {
SimpleDateFormat tst = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = tst.format(new Date());
return "Rechnung"+ timestamp + ".jpg";
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Bitmap bitmap = (Bitmap)data.getExtras().get("data");
//imageView.setImageBitmap(bitmap);
}
}`enter code here`
我制作了一个小应用程序,允许有意地打开相机并拍照。之后我在 imageView 中显示该图片。我的问题是,我想保存我拍摄的图像,该图像当前可在 imageview 上使用。如何将拍摄的图像保存到我的图库中并在图像视图中可用?我当前的代码是:
public class activity_auto extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto);
Button btnCamera= (Button)findViewById(R.id.btnCamera);
imageView=(ImageView)findViewById(R.id.imageView);
}
public void onButtonClicked(View v){
if(v.getId()==R.id.btnCamera) {
//starting camera function
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
if(v.getId()==R.id.goToGPS) {
Intent intent2 = new Intent(activity_auto.this, function_gps.class );
startActivity(intent2);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//initialize my imageview
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
imageView.setImageBitmap(bitmap);
}
}
错误日志:
06-30 11:37:25.759 2624-3776/? E/EGL_emulation: eglQueryContext 32c0 EGL_BAD_ATTRIBUTE
06-30 11:37:25.762 2624-3776/? E/EGL_emulation: tid 3776: eglQueryContext(1716): error 0x3004 (EGL_BAD_ATTRIBUTE)
06-30 11:37:26.600 1613-1624/? E/RecoverySystemService: Timed out connecting to uncrypt socket
06-30 11:37:26.600 1613-1624/? E/RecoverySystemService: Failed to connect to uncrypt socket
06-30 11:37:26.665 2412-3061/? E/SystemUpdateService: Failed to call RecoverySystem.cancelScheduledUpdate
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at xae.c(:com.google.android.gms:134)
at afuw.d(:com.google.android.gms:195)
at afuw.p(:com.google.android.gms:2178)
at afuw.a(:com.google.android.gms:448)
at afuw.doInBackground(:com.google.android.gms:50475)
at android.os.AsyncTask.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.io.IOException: cancel scheduled update failed
at android.os.RecoverySystem.cancelScheduledUpdate(RecoverySystem.java:555)
at java.lang.reflect.Method.invoke(Native Method)
at xae.c(:com.google.android.gms:134)
at afuw.d(:com.google.android.gms:195)
at afuw.p(:com.google.android.gms:2178)
at afuw.a(:com.google.android.gms:448)
at afuw.doInBackground(:com.google.android.gms:50475)
at android.os.AsyncTask.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.lang.Thread.run(Thread.java:761)
06-30 11:37:26.666 2412-3061/? E/SystemUpdateTask: exception trying to cancel scheduled update
java.io.IOException: Failed to invoke RecoverySystem.cancelScheduledUpdate
at xae.c(:com.google.android.gms:140)
at afuw.d(:com.google.android.gms:195)
at afuw.p(:com.google.android.gms:2178)
at afuw.a(:com.google.android.gms:448)
at afuw.doInBackground(:com.google.android.gms:50475)
at android.os.AsyncTask.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.lang.Thread.run(Thread.java:761)
06-30 11:37:33.447 3100-3100/com.group6.travlhoe E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.group6.travlhoe, PID: 3100
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.group6.travlhoe/com.group6.travlhoe.activity_auto}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at com.group6.travlhoe.activity_auto.onActivityResult(activity_auto.java:105)
at android.app.Activity.dispatchActivityResult(Activity.java:6915)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
06-30 11:37:40.070 3243-3264/? E/AppDataSearchHelper: Couldn't find corpus 'playlists'
编写此代码以保存图像
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG,90,bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try{
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
imageView.setImageBitmap(thumbnail);
imageView.setDrawingCacheEnabled(true);
Bitmap b = imageView.getDrawingCache();
MediaStore.Images.Media.insertImage(getContentResolver(),b,"Pics","Task5");
Toast.makeText(getApplicationContext(),"Image Saved",Toast.LENGTH_LONG).show();
}
在Manifest.xml
中写入此权限 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
转到设置 -> 应用程序 -> "Your App" -> 权限。允许访问相机和存储空间。
嗯,你有很多事情要做。
您需要清单和运行时中的存储权限,这本身就是一个主题。
您将需要处理外部存储以获取和使用文件夹来写入照片,并使用 ContentResolver 将照片从相机存储的位置复制到您应用程序的文件夹中。
如果您想在图库中查看照片,您还需要使用 MediaScannerConnection,以便对其进行编目并快速显示给用户。
我建议您按照一些教程进行操作。
从 Commonsware 中搜索 CWAC Cammera。他们在 Github 中有一个项目,您可以查看,如果您 google 多一点,您应该找到一个教程来解释该项目过程的每个步骤。
伙计们,我找到了将带有相机意图的照片添加到您的图库中的最佳方法:
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class activity_auto extends AppCompatActivity {
private BottomNavigationView bottomNavigationView;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto);
ImageButton btnCamera= (ImageButton)findViewById(R.id.btnCamera);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
}
public void onButtonClicked(View v){
if(v.getId()==R.id.btnCamera) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureName= getPictureName();
File imageFile= new File(pictureDirectory,pictureName);
//URI weil putExtra sonst nicht mit File elementen klar kommt!
Uri pictureUri = Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
startActivityForResult(intent, 0);
}
if(v.getId()==R.id.goToGPS) {
Intent intent2 = new Intent(activity_auto.this, function_gps.class );
startActivity(intent2);
}
}
private String getPictureName() {
SimpleDateFormat tst = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = tst.format(new Date());
return "Rechnung"+ timestamp + ".jpg";
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Bitmap bitmap = (Bitmap)data.getExtras().get("data");
//imageView.setImageBitmap(bitmap);
}
}`enter code here`