本帖原创,转发请标记出处。实在是本人一些肤浅的经验之谈,大神可绕行。另外如有不足之处或者可以优化的地方
欢迎指出,万分感谢。只为相互学习和进步。如果能对您有所帮助或者启发,便是我最开心的事。
最近写了类似微信朋友圈的功能,这就涉及到关于图片的处理
图片的处理 要考虑用户端的显示 和服务器端的存储能力
因此图片要尽可能的清楚 又要尽可能的小 还要尽可能加载的快 缓存与回收的好
这就需做要做很多的工作
先说第一部分:图片的获取
一来自于拍照 二来源于相册中选取
1.拍照
思路:调用系统相机拍照,注意拍照权限,在onActivityResult方法中处理得到的Bitmap或者图片地址
public void photo() { //执行拍照前,应该先判断SD卡是否存在 String SDState = Environment.getExternalStorageState(); if (SDState.equals(Environment.MEDIA_MOUNTED)) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); /*** * 需要说明一下,以下操作使用照相机拍照,拍照后的图片会存放在相册中的 * 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图 * 如果不实用ContentValues存放照片路径的话,拍照后获取的图片为缩略图不清晰 */ ContentValues values = new ContentValues(); mPhotoUri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mPhotoUri); startActivityForResult(intent, TAKE_PICTURE); } else { BaseApp.getInstance().showInformation(R.string.network_no_sdcard); } }
/** * 结果返回调用 * * @param requestCode * @param resultCode * @param data */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case TAKE_PICTURE: if (Bimp.drr.size() < 9 && resultCode == RESULT_OK) {//从拍照回调的结果 if (mPhotoUri == null) { BaseApp.getInstance().showInformation(R.string.userinfo_error_select_picture); } else { String[] pojo = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(mPhotoUri, pojo, null, null, null); if (cursor != null) { int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]); cursor.moveToFirst(); path = cursor.getString(columnIndex); cursor.close(); } Bimp.drr.add(path); mPhotoAdapter.update(); } } break; case 101://刷新方法 mPhotoAdapter.update(); break; } }2.从相册中选择 从系统中得到要存放图片的路径 然后用adapter展示 再选择 (请参看最后专辑帮助类)
import android.app.Activity; import android.graphics.Bitmap; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.List; import cn.ninebot.ninebot.BaseApp; import cn.ninebot.ninebot.R; public class ImageBucketAdapter extends BaseAdapter { final String TAG = getClass().getSimpleName(); Activity act; /** * 图片集列表 */ List<ImageBucket> dataList; BitmapCache cache; BitmapCache.ImageCallback callback = new BitmapCache.ImageCallback() { @Override public void imageLoad(ImageView imageView, Bitmap bitmap, Object... params) { if (imageView != null && bitmap != null) { String url = (String) params[0]; if (url != null && url.equals((String) imageView.getTag())) { ((ImageView) imageView).setImageBitmap(bitmap); } else { Log.e(TAG, "callback, bmp not match"); } } else { Log.e(TAG, "callback, bmp null"); } } }; public ImageBucketAdapter(Activity act, List<ImageBucket> list) { this.act = act; dataList = list; cache = new BitmapCache(); } @Override public int getCount() { // TODO Auto-generated method stub int count = 0; if (dataList != null) { count = dataList.size(); } return count; } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } class Holder { private ImageView iv; private ImageView selected; private TextView name; private TextView count; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { // TODO Auto-generated method stub Holder holder; if (arg1 == null) { holder = new Holder(); arg1 = View.inflate(act, R.layout.friends_cricle_add_image_bucket, null); holder.iv = (ImageView) arg1.findViewById(R.id.image); holder.selected = (ImageView) arg1.findViewById(R.id.isselected); holder.name = (TextView) arg1.findViewById(R.id.tvName); holder.count = (TextView) arg1.findViewById(R.id.count); arg1.setTag(holder); } else { holder = (Holder) arg1.getTag(); } ImageBucket item = dataList.get(arg0); holder.count.setText("" + item.count); holder.name.setText(item.bucketName); holder.selected.setVisibility(View.GONE); if (item.imageList != null && item.imageList.size() > 0) { String thumbPath = item.imageList.get(0).thumbnailPath; String sourcePath = item.imageList.get(0).imagePath; holder.iv.setTag(sourcePath); // cache.displayBmp(holder.iv, thumbPath, sourcePath, callback); cache.displayBmp(holder.iv, sourcePath, sourcePath, callback); } else { holder.iv.setImageBitmap(null); Log.e(TAG, "no images in bucket " + item.bucketName); } return arg1; } }
专辑帮助类 /** * 专辑帮助类 * * @author Administrator * */ public class AlbumHelper { final String TAG = getClass().getSimpleName(); Context mContext; ContentResolver mContentResolver; // 缩略图列表 HashMap<String, String> mThumbnailList = new HashMap<String, String>(); // 专辑列表 List<HashMap<String, String>> mAlbumList = new ArrayList<HashMap<String, String>>(); HashMap<String, ImageBucket> mBucketList = new HashMap<String, ImageBucket>(); private static AlbumHelper instance; private AlbumHelper() { } public static AlbumHelper getHelper() { if (instance == null) { instance = new AlbumHelper(); } return instance; } /** * 初始化 * * @param context */ public void init(Context context) { if (this.mContext == null) { this.mContext = context; mContentResolver = context.getContentResolver(); } } /** * 得到缩略图 */ private void getThumbnail() { String[] projection = { Thumbnails._ID, Thumbnails.IMAGE_ID,Thumbnails.DATA }; Cursor cursor = mContentResolver.query(Thumbnails.EXTERNAL_CONTENT_URI, projection,null, null, null); getThumbnailColumnData(cursor); } /** * 从数据库中得到缩略图 * * @param cur */ private void getThumbnailColumnData(Cursor cur) { if (cur.moveToFirst()) { int _id; int image_id; String image_path; int _idColumn = cur.getColumnIndex(Thumbnails._ID); int image_idColumn = cur.getColumnIndex(Thumbnails.IMAGE_ID); int dataColumn = cur.getColumnIndex(Thumbnails.DATA); do { // Get the field values _id = cur.getInt(_idColumn); image_id = cur.getInt(image_idColumn); image_path = cur.getString(dataColumn); mThumbnailList.put("" + image_id, image_path); } while (cur.moveToNext()); } } /** * 得到原图 */ void getAlbum() { String[] projection = { Albums._ID, Albums.ALBUM, Albums.ALBUM_ART,Albums.ALBUM_KEY, Albums.ARTIST, Albums.NUMBER_OF_SONGS }; Cursor cursor = mContentResolver.query(Albums.EXTERNAL_CONTENT_URI, projection, null,null, null); getAlbumColumnData(cursor); } /** * 从本地数据库中得到原图 * * @param cur */ private void getAlbumColumnData(Cursor cur) { if (cur.moveToFirst()) { int _id; String album; String albumArt; String albumKey; String artist; int numOfSongs; int _idColumn = cur.getColumnIndex(Albums._ID); int albumColumn = cur.getColumnIndex(Albums.ALBUM); int albumArtColumn = cur.getColumnIndex(Albums.ALBUM_ART); int albumKeyColumn = cur.getColumnIndex(Albums.ALBUM_KEY); int artistColumn = cur.getColumnIndex(Albums.ARTIST); int numOfSongsColumn = cur.getColumnIndex(Albums.NUMBER_OF_SONGS); do { // Get the field values _id = cur.getInt(_idColumn); album = cur.getString(albumColumn); albumArt = cur.getString(albumArtColumn); albumKey = cur.getString(albumKeyColumn); artist = cur.getString(artistColumn); numOfSongs = cur.getInt(numOfSongsColumn); // Do something with the values. Log.i(TAG, _id + " album:" + album + " albumArt:" + albumArt + "albumKey: " + albumKey + " artist: " + artist + " numOfSongs: " + numOfSongs + "---"); HashMap<String, String> hash = new HashMap<String, String>(); hash.put("_id", _id + ""); hash.put("album", album); hash.put("albumArt", albumArt); hash.put("albumKey", albumKey); hash.put("artist", artist); hash.put("numOfSongs", numOfSongs + ""); mAlbumList.add(hash); } while (cur.moveToNext()); } } /** * 是否创建了图片集 */ boolean hasBuildImagesBucketList = false; /** * 得到图片集 */ void buildImagesBucketList() { mBucketList.clear();//清空以免重复加载 long startTime = System.currentTimeMillis(); // 构造缩略图索引 getThumbnail(); // 构造相册索引 String columns[] = new String[] { Media._ID, Media.BUCKET_ID, Media.PICASA_ID, Media.DATA, Media.DISPLAY_NAME, Media.TITLE, Media.SIZE, Media.BUCKET_DISPLAY_NAME }; // 得到一个游标 Cursor cur = mContentResolver.query(Media.EXTERNAL_CONTENT_URI, columns, null, null, null); if (cur.moveToFirst()) { // 获取指定列的索引 int photoIDIndex = cur.getColumnIndexOrThrow(Media._ID); int photoPathIndex = cur.getColumnIndexOrThrow(Media.DATA); int photoNameIndex = cur.getColumnIndexOrThrow(Media.DISPLAY_NAME); int photoTitleIndex = cur.getColumnIndexOrThrow(Media.TITLE); int photoSizeIndex = cur.getColumnIndexOrThrow(Media.SIZE); int bucketDisplayNameIndex = cur .getColumnIndexOrThrow(Media.BUCKET_DISPLAY_NAME); int bucketIdIndex = cur.getColumnIndexOrThrow(Media.BUCKET_ID); int picasaIdIndex = cur.getColumnIndexOrThrow(Media.PICASA_ID); // 获取图片总数 int totalNum = cur.getCount(); do { String _id = cur.getString(photoIDIndex); String name = cur.getString(photoNameIndex); String path = cur.getString(photoPathIndex); String title = cur.getString(photoTitleIndex); String size = cur.getString(photoSizeIndex); String bucketName = cur.getString(bucketDisplayNameIndex); String bucketId = cur.getString(bucketIdIndex); String picasaId = cur.getString(picasaIdIndex); Log.i(TAG, _id + ", bucketId: " + bucketId + ", picasaId: " + picasaId + " name:" + name + " path:" + path + " title: " + title + " size: " + size + " bucket: " + bucketName + "---"); ImageBucket bucket = mBucketList.get(bucketId); if (bucket == null) { bucket = new ImageBucket(); mBucketList.put(bucketId, bucket); bucket.imageList = new ArrayList<ImageItem>(); bucket.bucketName = bucketName; } bucket.count++; ImageItem imageItem = new ImageItem(); imageItem.imageId = _id; imageItem.imagePath = path; imageItem.thumbnailPath = mThumbnailList.get(_id); bucket.imageList.add(imageItem); } while (cur.moveToNext()); } Iterator<Entry<String, ImageBucket>> itr = mBucketList.entrySet().iterator(); while (itr.hasNext()) { Entry<String, ImageBucket> entry = (Entry<String, ImageBucket>) itr.next(); ImageBucket bucket = entry.getValue(); Log.d(TAG, entry.getKey() + ", " + bucket.bucketName + ", "+ bucket.count + " ---------- "); for (int i = 0; i < bucket.imageList.size(); ++i) { ImageItem image = bucket.imageList.get(i); Log.d(TAG, "----- " + image.imageId + ", " + image.imagePath+ ", " + image.thumbnailPath); } } hasBuildImagesBucketList = true; long endTime = System.currentTimeMillis(); Log.d(TAG, "use time: " + (endTime - startTime) + " ms"); } /** * 得到图片集 * * @param refresh * @return */ public List<ImageBucket> getImagesBucketList(boolean refresh) { if (refresh || (!refresh && !hasBuildImagesBucketList)) { buildImagesBucketList(); } List<ImageBucket> tmpList = new ArrayList<ImageBucket>(); Iterator<Entry<String, ImageBucket>> itr = mBucketList.entrySet().iterator(); while (itr.hasNext()) { Entry<String, ImageBucket> entry = (Entry<String, ImageBucket>) itr.next(); tmpList.add(entry.getValue()); } return tmpList; } /** * 得到原始图像路径 * * @param image_id * @return */ String getOriginalImagePath(String image_id) { String path = null; Log.i(TAG, "---(^o^)----" + image_id); String[] projection = { Media._ID, Media.DATA }; Cursor cursor = mContentResolver.query(Media.EXTERNAL_CONTENT_URI, projection,Media._ID + "=" + image_id, null, null); if (cursor != null) { cursor.moveToFirst(); path = cursor.getString(cursor.getColumnIndex(Media.DATA)); } return path; } }