简单的说就是把选择的图片转换成bitmap 并存入集合。然后给GrideView设置数据并显示。
直接代码走起来
这是主要的act
/**
* 需求是要求最多三个图片
* Created by BJColor on 2016/7/28.
*/
public class SelectPhoto extends Activity {
private MyPhotoAdapter myPhotoAdapter;//自己的adapter
private int selectPoohtoPoistion;//选中的是第几个position
private ArrayList<Bitmap> comeBacePhotoList;//存放加入进来的bitmap
private String imgurlB64;
@Bind(R.id.gv_photo)
GridView gvPhoto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_seletphoto);
ButterKnife.bind(this);
comeBacePhotoList = new ArrayList<Bitmap>();//存放加入进来的bitmap
myPhotoAdapter = new MyPhotoAdapter(this);
gvPhoto.setAdapter(myPhotoAdapter);
myPhotoAdapter.update();
gvPhoto.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectPoohtoPoistion = position;
//这一部分是调用系统相册
Intent i = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
private static int RESULT_LOAD_IMAGE = 1;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Bitmap bitmap = BitmapUtils.convertToBitmap(picturePath, 400, 400);
imgurlB64 = BitmapUtils.bitmapToBase64(bitmap);
cursor.close();
//没到三个图片的时候
if (comeBacePhotoList.size() < 3) {
comeBacePhotoList.add(bitmap);
myPhotoAdapter.update();
return;
}
//当有三个图片的时候 在点击图片就和可以替换当前位置的图片
if (comeBacePhotoList.size() == 3) {
comeBacePhotoList.remove(selectPoohtoPoistion);
comeBacePhotoList.add(selectPoohtoPoistion, bitmap);
}
myPhotoAdapter.update();
}
}
private class MyPhotoAdapter extends BaseAdapter {
private LayoutInflater inflater;
private MyPhotoAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
if(comeBacePhotoList.size()==0){
return 1;
}
return comeBacePhotoList.size();
}
public Object getItem(int arg0) {
return arg0;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.photoitem,
parent, false);
holder = new ViewHolder();
holder.image = (ImageView) convertView
.findViewById(R.id.item_grida_image);
holder.image_delete = (ImageView) convertView
.findViewById(R.id.iv_deletephoto);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (comeBacePhotoList.size()==0) {//当这个集合为空的时候 设置第一个为默认图片
holder.image_delete.setVisibility(View.GONE);
holder.image.setImageBitmap(BitmapFactory.decodeResource(
getResources(), R.mipmap.xiaoxiangji));
} else {//其他的从这个集合里面获取bitmap 并设置 并且显示右上方的小X号
holder.image_delete.setVisibility(View.VISIBLE);
holder.image.setImageBitmap(comeBacePhotoList.get(position));
}
//设置x号的点击事件
holder.image_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
comeBacePhotoList.remove(position);//移除脚标相对应的值
update();
}
});
return convertView;
}
public void update() {//刷新
myPhotoAdapter.notifyDataSetChanged();
}
public class ViewHolder {
public ImageView image;
public ImageView image_delete;
}
}
@Override
protected void onRestart() {
myPhotoAdapter.update();
super.onRestart();
}
}
bitmapUtils
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
/**
* 图片相关的工具类
*/
public class BitmapUtils {
public static boolean saveBitmapToSD(Bitmap bitmap, String dir, String name, boolean isShowPhotos) {
File path = new File(dir);
if (!path.exists()) {
path.mkdirs();
}
File file = new File(path + "/" + name);
if (file.exists()) {
file.delete();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
return false;
}
} else {
return true;
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100,
fileOutputStream);
fileOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 其次把文件插入到系统图库
if (isShowPhotos) {
try {
MediaStore.Images.Media.insertImage(MyApplication.getIntstance().getContentResolver(),
file.getAbsolutePath(), name, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 最后通知图库更新
MyApplication.getIntstance().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file)));
}
return true;
}
public static boolean saveResToSD(Context context, int resID, String dir, String name) {
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resID);
return saveBitmapToSD(bitmap, dir, name, false);
}
public static Bitmap convertToBitmap(String path, int w, int h) {
BitmapFactory.Options opts = new BitmapFactory.Options();
// 设置为ture只获取图片大小
opts.inJustDecodeBounds = true;
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
// 返回为空
BitmapFactory.decodeFile(path, opts);
int width = opts.outWidth;
int height = opts.outHeight;
float scaleWidth = 0.f, scaleHeight = 0.f;
if (width > w || height > h) {
// 缩放
scaleWidth = ((float) width) / w;
scaleHeight = ((float) height) / h;
}
opts.inJustDecodeBounds = false;
float scale = Math.max(scaleWidth, scaleHeight);
opts.inSampleSize = (int)scale;
WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
return Bitmap.createScaledBitmap(weak.get(), w, h, true);
}
public static String bitmapToBase64(Bitmap bitmap) {
String result = null;
ByteArrayOutputStream baos;
baos = null;
try {
if (bitmap != null) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baos.flush();
baos.close();
byte[] bitmapBytes = baos.toByteArray();
result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.flush();
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* base64转为bitmap
* @param base64Data
* @return
*/
public static Bitmap base64ToBitmap(String base64Data) {
byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
}