最近开发的项目中需要手机相册和相机功能我就在各种博客中找到了一些资料在综合我的就可以实现多张照片的展示
自我感觉要比其它的博客写的详细。
直接上图了大家:
直接上代码:
千万不要忘记在清单文件中加上权限:
xml中的代码:
Activity中的代码
import android.app.Activity;
import android.content.ContentResolver;
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.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import utils.ImageTools;
/**
* Created by big_cow on 2016/11/29.
*/
public class TakePhotoActivity extends Activity {
private static final int TAKE_PICTURE = 0; // 相机
private static final int CHOOSE_PICTURE = 1; // 图片
private static final int SCALE = 5;//照片缩小比例
private ImageView takePhoto_picture, takePhotot_photo, takePhoto_picture2,
takePhoto_picture3, takePhoto_picture4, takePhoto_picture5;
private TextView takePhotot_text;
private TextView takePhoto_jump;
private ImageView[] imageViews;
// 存放图片路径
private ArrayList mList = new ArrayList();
private HashMap map = new HashMap();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.takephoto_item);
initView();
initButton_photo();
initButoon_jump();
}
private void initView() {
takePhotot_photo = (ImageView) findViewById(R.id.takephoto_photo);// 相机
takePhotot_text = (TextView) findViewById(R.id.takephoto_text); // 相册
takePhoto_picture = (ImageView) findViewById(R.id.takephoto_picture); // 图片
takePhoto_picture2 = (ImageView) findViewById(R.id.takephoto_picture2); // 图片
takePhoto_picture3 = (ImageView) findViewById(R.id.takephoto_picture3); // 图片
takePhoto_picture4 = (ImageView) findViewById(R.id.takephoto_picture4); // 图片
takePhoto_picture5 = (ImageView) findViewById(R.id.takephoto_picture5); // 图片
/*
imageViews = new ImageView[]
{takePhoto_picture, takePhoto_picture2, takePhoto_picture3, takePhoto_picture4, takePhoto_picture5};*/
takePhoto_jump = (TextView) findViewById(R.id.takephtot_jump); //发表
}
// 相机相册点击事件
private void initButton_photo() {
takePhotot_photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.jpg"));
//指定照片保存路径(SD卡),image.jpg为一个临时文件,每次拍照后这个图片都会被替换
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(openCameraIntent, TAKE_PICTURE);
}
});
takePhotot_text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
openAlbumIntent.setType("image/*");
startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case TAKE_PICTURE:
takePhoto();
break;
case CHOOSE_PICTURE:
takePicture(data);
break;
default:
break;
}
}
}
private void takePicture(Intent data) {
ContentResolver resolver = getContentResolver();
//照片的原始资源地址
Uri originalUri = data.getData();
try {
//使用ContentProvider通过URI获取原始图片
Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
if (photo != null) {
//为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始Bitmap占用的内存
Bitmap smallBitmap = ImageTools.zoomBitmap(photo, photo.getWidth() / SCALE,
photo.getHeight() / SCALE);
//释放原始图片占用的内存,防止out of memory异常发生
photo.recycle();
switch (map.size()) {
case 0:
takePhoto_picture.setImageBitmap(smallBitmap);
map.put(takePhoto_picture, PictureType.PICTURE);
String s = originalUri.toString();
mList.add(s);
break;
case 1:
takePhoto_picture2.setImageBitmap(smallBitmap);
map.put(takePhoto_picture2, PictureType.PICTURE);
Uri picture_uri2 = data.getData();
// 把Uri转化成String类型
String s2 = originalUri.toString();
mList.add(s2);
break;
case 2:
takePhoto_picture3.setImageBitmap(smallBitmap);
map.put(takePhoto_picture3, PictureType.PICTURE);
Uri picture_uri3 = data.getData();
String s3 = originalUri.toString();
mList.add(s3);
break;
case 3:
takePhoto_picture4.setImageBitmap(smallBitmap);
map.put(takePhoto_picture4, PictureType.PICTURE);
Uri picture_uri4 = data.getData();
String s4 = originalUri.toString();
mList.add(s4);
break;
case 4:
takePhoto_picture5.setImageBitmap(smallBitmap);
map.put(takePhoto_picture5, PictureType.PICTURE);
Uri picture_uri5 = data.getData();
String s5 = originalUri.toString();
mList.add(s5);
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void takePhoto() {
//将保存在本地的图片取出并缩小后显示在界面上
Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/image.jpg");
Bitmap newBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
//由于Bitmap内存占用较大,这里需要回收内存,否则会报out of memory异常
bitmap.recycle();
//将处理过的图片显示在界面上,
switch (map.size()) {
// 如果位置等于0的时候我们往HashMap中添加第一个图片,以后就以此类推
case 0:
takePhoto_picture.setImageBitmap(newBitmap);
map.put(takePhoto_picture, PictureType.PHOTO);
break;
case 1:
takePhoto_picture2.setImageBitmap(newBitmap);
map.put(takePhoto_picture2, PictureType.PHOTO);
break;
case 2:
takePhoto_picture3.setImageBitmap(newBitmap);
map.put(takePhoto_picture3, PictureType.PHOTO);
break;
case 3:
takePhoto_picture4.setImageBitmap(newBitmap);
map.put(takePhoto_picture4, PictureType.PHOTO);
break;
case 4:
takePhoto_picture5.setImageBitmap(newBitmap);
map.put(takePhoto_picture5, PictureType.PHOTO);
break;
}
// 并保存到本地
ImageTools.savePhotoToSDCard(newBitmap, Environment.getExternalStorageDirectory().getAbsolutePath(),
String.valueOf(System.currentTimeMillis()));
}
// 第一个枚举
enum PictureType {
PHOTO, PICTURE
}
}
有一个获取相机图片压缩的工具类这个是我在其它博客查找的资料,主要功能减小内存的使用,优化程序的性能,我感觉蛮不错的我就给copy过来了
public final class ImageTools {
/**
* Transfer drawable to bitmap
*
* @param drawable
* @return
*/
public static Bitmap drawableToBitmap(Drawable drawable) {
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}
/**
* Bitmap to drawable
*
* @param bitmap
* @return
*/
public static Drawable bitmapToDrawable(Bitmap bitmap) {
return new BitmapDrawable(bitmap);
}
/**
* Input stream to bitmap
*
* @param inputStream
* @return
* @throws Exception
*/
public static Bitmap inputStreamToBitmap(InputStream inputStream)
throws Exception {
return BitmapFactory.decodeStream(inputStream);
}
/**
* Byte transfer to bitmap
*
* @param byteArray
* @return
*/
public static Bitmap byteToBitmap(byte[] byteArray) {
if (byteArray.length != 0) {
return BitmapFactory
.decodeByteArray(byteArray, 0, byteArray.length);
} else {
return null;
}
}
/**
* Byte transfer to drawable
*
* @param byteArray
* @return
*/
public static Drawable byteToDrawable(byte[] byteArray) {
ByteArrayInputStream ins = null;
if (byteArray != null) {
ins = new ByteArrayInputStream(byteArray);
}
return Drawable.createFromStream(ins, null);
}
public static byte[] bitmapToBytes(Bitmap bm) {
byte[] bytes = null;
if (bm != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
bytes = baos.toByteArray();
}
return bytes;
}
/**
* Drawable transfer to bytes
*
* @param drawable
* @return
*/
public static byte[] drawableToBytes(Drawable drawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
byte[] bytes = bitmapToBytes(bitmap);
;
return bytes;
}
/**
* Base64 to byte[]
// */
// public static byte[] base64ToBytes(String base64) throws IOException {
// byte[] bytes = Base64.decode(base64);
// return bytes;
// }
//
// /**
// * Byte[] to base64
// */
// public static String bytesTobase64(byte[] bytes) {
// String base64 = Base64.encode(bytes);
// return base64;
// }
/**
* Create reflection images
*
* @param bitmap
* @return
*/
public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
final int reflectionGap = 4;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, h / 2, w,
h / 2, matrix, false);
Bitmap bitmapWithReflection = Bitmap.createBitmap(w, (h + h / 2),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(bitmap, 0, 0, null);
Paint deafalutPaint = new Paint();
canvas.drawRect(0, h, w, h + reflectionGap, deafalutPaint);
canvas.drawBitmap(reflectionImage, 0, h + reflectionGap, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
0x00ffffff, Shader.TileMode.CLAMP);
paint.setShader(shader);
// Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
// Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, h, w, bitmapWithReflection.getHeight()
+ reflectionGap, paint);
return bitmapWithReflection;
}
/**
* Get rounded corner images
*
* @param bitmap
* @param roundPx 5 10
* @return
*/
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Bitmap output = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, w, h);
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
/**
* Resize the bitmap
*
* @param bitmap
* @param width
* @param height
* @return
*/
public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) width / w);
float scaleHeight = ((float) height / h);
matrix.postScale(scaleWidth, scaleHeight);
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
return newbmp;
}
/**
* Resize the drawable
*
* @param drawable
* @param w
* @param h
* @return
*/
public static Drawable zoomDrawable(Drawable drawable, int w, int h) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Bitmap oldbmp = drawableToBitmap(drawable);
Matrix matrix = new Matrix();
float sx = ((float) w / width);
float sy = ((float) h / height);
matrix.postScale(sx, sy);
Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height,
matrix, true);
return new BitmapDrawable(newbmp);
}
/**
* Get images from SD card by path and the name of image
*
* @param photoName
* @return
*/
public static Bitmap getPhotoFromSDCard(String path, String photoName) {
Bitmap photoBitmap = BitmapFactory.decodeFile(path + "/" + photoName + ".png");
if (photoBitmap == null) {
return null;
} else {
return photoBitmap;
}
}
/**
* Check the SD card
*
* @return
*/
public static boolean checkSDCardAvailable() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
public static boolean findPhotoFromSDCard(String path, String photoName) {
boolean flag = false;
if (checkSDCardAvailable()) {
File dir = new File(path);
if (dir.exists()) {
File folders = new File(path);
File photoFile[] = folders.listFiles();
for (int i = 0; i < photoFile.length; i++) {
String fileName = photoFile[i].getName().split("\\.")[0];
if (fileName.equals(photoName)) {
flag = true;
}
}
} else {
flag = false;
}
// File file = new File(path + "/" + photoName + ".jpg" );
// if (file.exists()) {
// flag = true;
// }else {
// flag = false;
// }
} else {
flag = false;
}
return flag;
}
/**
* Save image to the SD card
*
* @param photoBitmap
* @param photoName
* @param path
*/
public static void savePhotoToSDCard(Bitmap photoBitmap, String path, String photoName) {
if (checkSDCardAvailable()) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
File photoFile = new File(path, photoName + ".png");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(photoFile);
if (photoBitmap != null) {
if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
fileOutputStream.flush();
// fileOutputStream.close();
}
}
} catch (FileNotFoundException e) {
photoFile.delete();
e.printStackTrace();
} catch (IOException e) {
photoFile.delete();
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void deleteAllPhoto(String path) {
if (checkSDCardAvailable()) {
File folder = new File(path);
File[] files = folder.listFiles();
for (int i = 0; i < files.length; i++) {
files[i].delete();
}
}
}
public static void deletePhotoAtPathAndName(String path, String fileName) {
if (checkSDCardAvailable()) {
File folder = new File(path);
File[] files = folder.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].getName().split("\\.")[0].equals(fileName)) {
files[i].delete();
}
}
}
}
}