需求:从本地相册找图片,或通过调用系统相机拍照得到图片。
容易出错的地方:
1、当我们指定了照片的uri路径,我们就不能通过data.getData();来获取uri,而应该直接拿到uri(用全局变量或者其他方式)然后设置给imageVIEw
imageVIEw.setimageURI(uri);
2、我发现手机前置摄像头拍出来的照片只有几百KB,直接用imageVIEw.setimageURI(uri);没有很大问题,但是后置摄像头拍出来的照片比较大,这个时候使用imageVIEw.setimageURI(uri);就容易出现 out of memory(oom)错误,我们需要先把URI转换为Bitmap,再压缩bitmap,然后通过imageVIEw.setimageBitmap(bitmap);来显示图片。
3、将照片存放到SD卡中后,照片不能立即出现在系统相册中,因此我们需要发送广播去提醒相册更新照片。
4、这里用到了sharepreference,要注意用完之后移除缓存。
代码:
MainActivity:
package com.sctu.edu.test;import androID.content.Intent;import androID.graphics.Bitmap;import androID.graphics.BitmapFactory;import androID.net.Uri;import androID.os.Bundle;import androID.os.Environment;import androID.provIDer.MediaStore;import androID.support.v7.app.AppCompatActivity;import androID.util.Log;import androID.vIEw.VIEw;import androID.Widget.ImageVIEw;import com.sctu.edu.test.tools.Imagetools;import java.io.file;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;public class MainActivity extends AppCompatActivity { private static final int PHOTO_FROM_galLERY = 1; private static final int PHOTO_FROM_CAMERA = 2; private ImageVIEw imageVIEw; private file appDir; private Uri uriForCamera; private Date date; private String str = ""; private SharePreference sharePreference; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); //AndroID不推荐使用全局变量,我在这里使用了sharePreference sharePreference = SharePreference.getInstance(this); imageVIEw = (ImageVIEw) findVIEwByID(R.ID.imageVIEw); } //从相册取图片 public voID gallery(VIEw vIEw) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent,PHOTO_FROM_galLERY); } //拍照取图片 public voID camera(VIEw vIEw) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); uriForCamera = Uri.fromfile(createImageStoragePath()); sharePreference.setCache("uri",String.valueOf(uriForCamera)); /** * 指定了uri路径,startActivityForResult不返回intent, * 所以在onActivityResult()中不能通过data.getData()获取到uri; */ intent.putExtra(MediaStore.EXTRA_OUTPUT,uriForCamera); startActivityForResult(intent,PHOTO_FROM_CAMERA); } @OverrIDe protected voID onActivityResult(int requestCode,int resultCode,Intent data) { super.onActivityResult(requestCode,resultCode,data); //第一层switch switch (requestCode) { case PHOTO_FROM_galLERY: //第二层switch switch (resultCode) { case RESulT_OK: if (data != null) { Uri uri = data.getData(); imageVIEw.setimageURI(uri); } break; case RESulT_CANCELED: break; } break; case PHOTO_FROM_CAMERA: if (resultCode == RESulT_OK) { Uri uri = Uri.parse(sharePreference.getString("uri")); updateDCIM(uri); try { //把URI转换为Bitmap,并将bitmap压缩,防止OOM(out of memory) Bitmap bitmap = Imagetools.getBitmapFromUri(uri,this); imageVIEw.setimageBitmap(bitmap); } catch (IOException e) { e.printstacktrace(); } removeCache("uri"); } else { Log.e("result","is not ok" + resultCode); } break; default: break; } } /** * 设置相片存放路径,先将照片存放到SD卡中,再 *** 作 * * @return */ private file createImageStoragePath() { if (hasSdcard()) { appDir = new file("/sdcard/testimage/"); if (!appDir.exists()) { appDir.mkdirs(); } SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); date = new Date(); str = simpleDateFormat.format(date); String filename = str + ".jpg"; file file = new file(appDir,filename); return file; } else { Log.e("sd","is not load"); return null; } } /** * 将照片插入系统相册,提醒相册更新 * * @param uri */ private voID updateDCIM(Uri uri) { Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_file); intent.setData(uri); this.sendbroadcast(intent); Bitmap bitmap = BitmapFactory.decodefile(uri.getPath()); MediaStore.Images.Media.insertimage(getContentResolver(),bitmap,"",""); } /** * 判断SD卡是否可用 * * @return */ private boolean hasSdcard() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } /** * 移除缓存 * * @param cache */ private voID removeCache(String cache) { if (sharePreference.ifHaveShare(cache)) { sharePreference.removeOneCache(cache); } else { Log.e("this cache","is not exist."); } }}
Imagetools:
package com.sctu.edu.test.tools;import androID.app.Activity;import androID.graphics.Bitmap;import androID.graphics.BitmapFactory;import androID.net.Uri;import java.io.ByteArrayinputStream;import java.io.ByteArrayOutputStream;import java.io.fileNotFoundException;import java.io.IOException;import java.io.inputStream;public class Imagetools { /** * 通过uri获取图片并进行压缩 * * @param uri * @param activity * @return * @throws IOException */ public static Bitmap getBitmapFromUri(Uri uri,Activity activity) throws IOException { inputStream inputStream = activity.getContentResolver().openinputStream(uri); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inDither = true; options.inPreferredConfig = Bitmap.Config.ARGB_8888; BitmapFactory.decodeStream(inputStream,null,options); inputStream.close(); int originalWIDth = options.outWIDth; int originalHeight = options.outHeight; if (originalWIDth == -1 || originalHeight == -1) { return null; } float height = 800f; float wIDth = 480f; int be = 1; //be=1表示不缩放 if (originalWIDth > originalHeight && originalWIDth > wIDth) { be = (int) (originalWIDth / wIDth); } else if (originalWIDth < originalHeight && originalHeight > height) { be = (int) (originalHeight / height); } if (be <= 0) { be = 1; } BitmapFactory.Options bitmapOptinos = new BitmapFactory.Options(); bitmapOptinos.inSampleSize = be; bitmapOptinos.inDither = true; bitmapOptinos.inPreferredConfig = Bitmap.Config.ARGB_8888; inputStream = activity.getContentResolver().openinputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(inputStream,bitmapOptinos); inputStream.close(); return compressImage(bitmap); } /** * 质量压缩方法 * * @param bitmap * @return */ public static Bitmap compressImage(Bitmap bitmap) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream); int options = 100; while (byteArrayOutputStream.toByteArray().length / 1024 > 100) { byteArrayOutputStream.reset(); //第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差 ,第三个参数:保存压缩后的数据的流 bitmap.compress(Bitmap.CompressFormat.JPEG,options,byteArrayOutputStream); options -= 10; } ByteArrayinputStream byteArrayinputStream = new ByteArrayinputStream(byteArrayOutputStream.toByteArray()); Bitmap bitmAPImage = BitmapFactory.decodeStream(byteArrayinputStream,null); return bitmAPImage; }}
AndroIDMainfest.xml:
<?xml version="1.0" enCoding="utf-8"?><manifest package="com.sctu.edu.test" xmlns:androID="http://schemas.androID.com/apk/res/androID"> <uses-feature androID:name="androID.harDWare.camera" androID:required="true" /> <uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission androID:name="androID.permission.CAMERA"/> <uses-permission androID:name="androID.permission.MOUNT_UNMOUNT_fileSYstemS"/> <uses-permission androID:name="com.miui.whetstone.permission.ACCESS_PROVIDER"/> <uses-permission androID:name="androID.permission.READ_EXTERNAL_STORAGE"/> <uses-feature androID:name="androID.harDWare.camera.autofocus" /> <application androID:allowBackup="true" androID:icon="@mipmap/ic_launcher" androID:label="@string/app_name" androID:supportsRtl="true" androID:theme="@style/Apptheme"> <activity androID:name=".MainActivity"> <intent-filter> <action androID:name="androID.intent.action.MAIN"/> <category androID:name="androID.intent.category.LAUNCHER"/> </intent-filter> </activity> </application></manifest>
activity_main.xml:
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:background="#fff" androID:orIEntation="vertical" tools:context="com.sctu.edu.test.MainActivity"> <button androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="从图库找图片" androID:ID="@+ID/gallery" androID:onClick="gallery" androID:background="#ccc" androID:textSize="20sp" androID:padding="10dp" androID:layout_marginleft="30dp" androID:layout_margintop="40dp" /> <button androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="拍照获取图片" androID:ID="@+ID/camera" androID:onClick="camera" androID:background="#ccc" androID:textSize="20sp" androID:padding="10dp" androID:layout_marginleft="30dp" androID:layout_margintop="40dp" /> <ImageVIEw androID:layout_wIDth="300dp" androID:layout_height="300dp" androID:ID="@+ID/imageVIEw" androID:scaleType="fitXY" androID:background="@mipmap/ic_launcher" androID:layout_margintop="40dp" androID:layout_marginleft="30dp" /></linearLayout>
效果图:
或许有人会问,在AndroID6.0上面怎么点击拍照就出现闪退,那是因为我设置的最高SDK版本大于23,而我现在还没对运行时权限做处理,也许我会在下一篇博客里处理这个问题。谢谢浏览,希望对你有帮助!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
以上是内存溢出为你收集整理的Android获取本地相册图片和拍照获取图片的实现方法全部内容,希望文章能够帮你解决Android获取本地相册图片和拍照获取图片的实现方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)