public class BitmapLruCache extends LruCache<String, Bitmap> implements ImageCache { public BitmapLruCache(int maxSize) { super(maxSize); } @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight(); } @Override public Bitmap getBitmap(String url) { return get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { put(url, bitmap); }}
圆型图片
/** * Normal Icon 控件 计算保存各个绘画区域,按照设置,指定画不同图片。 * * @author bonty */ public class CircleImage extends NetworkImageView { protected Rect iconRect = null; protected Paint paint = null; public CircleImage(Context context) { this(context, null); } public CircleImage(Context context, AttributeSet attrs) { super(context, attrs); setDefaultImageResId(R.drawable.ease_default_avatar); } public CircleImage(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void build(String url) { setImageUrl(url, MyVolley.getInstance().getImageLoader()); } public void build(String s, ImageLoader.ImageListener imageCallback) { build(s); MyVolley.getInstance().getImageLoader().get(s, imageCallback); } /** * solve Volley's networkimageview - setimagebitmap method doesn't work */ private Bitmap mLocalBitmap; private boolean mShowLocal; public void setLocalImageBitmap(Bitmap bitmap) { if (bitmap != null) { mShowLocal = true; } this.mLocalBitmap = bitmap; requestLayout(); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (mShowLocal) { setImageBitmap(mLocalBitmap); } } @Override public void setImageUrl(String url, ImageLoader imageLoader) { mShowLocal = false; super.setImageUrl(url, imageLoader); } @Override public void setImageDrawable(Drawable drawable) { Bitmap iBitmap = ((BitmapDrawable) drawable).getBitmap(); if (iBitmap != null) { super.setImageDrawable(new BitmapDrawable( createCircleImage(iBitmap))); } } public static Bitmap createCircleImage(Bitmap bitmap) { return createCircleImage(bitmap, 0); } /** * 根据原图和变长绘制圆形图片 * * @param bitmap * @param icon * @return */ public static Bitmap createCircleImage(Bitmap bitmap, int icon) { if (bitmap == null) { return null; } int w = bitmap.getWidth(); int h = bitmap.getHeight(); if (w > h) { w = h; } int size = w; Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888); Canvas canvas = new Canvas(output); final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, size, size); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); canvas.drawCircle(w / 2, h / 2, size / 2, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); /** * 画最外层的大圆环 */ // int radius = size / 2 + 2; // 圆环的半径 // paint.setColor(HostApplication.aContext.getResources().getColor(android.R.color.black)); // 设置圆环的颜色 // paint.setStyle(Paint.Style.STROKE); // 设置空心 // paint.setStrokeWidth(8); // 设置圆环的宽度 // paint.setAntiAlias(true); // 消除锯齿 // canvas.drawCircle(w / 2, h / 2, radius, paint); // 画出圆环 return output; } }图片上传
public class HttpUtil { private static final String TAG = "HttpUtil"; public static String HttpMultipartRequestServer(String host,String url, List<NameValuePair> paramsList){ try { MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < paramsList.size(); index++) { // If the key equals to "image", we use FileBody to transfer // the data String pName = paramsList.get(index).getName(); if (pName.equalsIgnoreCase("file")) { entity.addPart(pName, new FileBody(new File(paramsList.get(index) .getValue()), "image/jpeg")); } else { // Normal string data entity.addPart(paramsList.get(index).getName(), new StringBody(paramsList.get(index).getValue(), Charset.forName("UTF-8"))); } } HttpPost request = new HttpPost(host + url); request.setEntity(entity); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity localEntity = response.getEntity(); return EntityUtils.toString(localEntity); } else { return ""; } } catch (Exception e) { Log.e(TAG,"", e); } return ""; } public static String HttpGetRequest(String url) { try { HttpGet request = new HttpGet(url); HttpResponse httpResponse = new DefaultHttpClient() .execute(request); if (httpResponse.getStatusLine().getStatusCode() == 200) { String result = EntityUtils.toString(httpResponse.getEntity()); return result; } } catch (Exception e) { Log.e(TAG, e.getMessage().toString()); } return ""; } }volley请求图片的封装
public class MyVolley { private static final int DEFAULT_DISK_USAGE_BYTES = 100 * 1024 * 1024; private static MyVolley sInstance = null; private RequestQueue mRequestQueue; private ImageLoader mImageLoader; private Handler mMainHandler; private MyVolley() { init(HostApplication.aContext); } public static MyVolley getInstance(){ if(null == sInstance){ synchronized (MyVolley.class){ if(null == sInstance){ sInstance = new MyVolley(); } } } return sInstance; } private synchronized void init(Context context) { String pictureParentDir =""; File file = HostApplication.aContext.getExternalCacheDir(); if(file!=null){ pictureParentDir = file.getAbsolutePath(); } File cacheDir = null; if(!TextUtils.isEmpty(pictureParentDir)){ cacheDir = new File(pictureParentDir); }else{ cacheDir = getCacheDir(context); if(null == cacheDir){ return; } } String userAgent = "volley/0"; try { String packageName = context.getPackageName(); PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); userAgent = packageName + "/" + info.versionCode; } catch (PackageManager.NameNotFoundException e) { } HttpStack stack; if (Build.VERSION.SDK_INT >= 9) { stack = new HurlStack(); } else { stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); } Network network = new BasicNetwork(stack); mRequestQueue = new RequestQueue(new DiskBasedCache(cacheDir,DEFAULT_DISK_USAGE_BYTES), network); mRequestQueue.start(); int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)) .getMemoryClass(); // Use 1/8th of the available memory for this memory cache. int cacheSize = 1024 * 1024 * memClass / 8; mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(cacheSize)); } private File getCacheDir(Context context) { File dir = context.getCacheDir(); if(null == dir){ return null; } File cacheDir = new File(dir.getAbsolutePath()+"/cm_image_cache/"); if(!cacheDir.exists()){ cacheDir.mkdirs(); } return cacheDir; } public synchronized DiskBasedCache getDiskBasedCache(){ return (DiskBasedCache)mRequestQueue.getCache(); } public synchronized boolean isCached(String url){ if(!TextUtils.isEmpty(url) && null != getDiskBasedCache()){ File file = getDiskBasedCache().getFileForKey(url); return file.exists(); } return false; } public synchronized ImageLoader getImageLoader() { if (mImageLoader != null) { return mImageLoader; } else { throw new IllegalStateException("ImageLoader not initialized"); } } public synchronized void preLoadImage(final String url,final ImageLoader.ImageListener listener){ if (null == url) { return; } if(isMainThread()){ getImageLoader().get(url,listener); }else{ if(mMainHandler == null){ mMainHandler = new Handler(Looper.getMainLooper()); } mMainHandler.post(new Runnable() { @Override public void run() { getImageLoader().get(url,listener); } }); } } public synchronized void loadImage(final ImageView image, String icon){ if (null == icon || null == image) { return; } getImageLoader().get(icon, new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { image.setImageBitmap(response.getBitmap()); } @Override public void onErrorResponse(VolleyError error) { } }); } private boolean isMainThread(){ return Looper.myLooper() == Looper.getMainLooper(); } }返回成功失败的接口
public interface ResultCallback{ void onSuccess(String response); void onFailed(VolleyError error); }
volley普通请求的封装
public class VolleyRequest { private static VolleyRequest mInstance; private RequestQueue mRequestQueue; private VolleyRequest() { init(HostApplication.aContext); } public static VolleyRequest getInstance() { if (mInstance == null) { synchronized (VolleyRequest.class) { if (mInstance == null) { mInstance = new VolleyRequest(); } } } return mInstance; } private synchronized void init(Context context) { mRequestQueue = Volley.newRequestQueue(context); } public void volleyPost(String url, final HashMap<String, String> hashMap, final ResultCallback resultCallback) { volleyPost(url, hashMap, resultCallback,false, null); } public void volleyPost(String url, final HashMap<String, String> hashMap, final ResultCallback resultCallback,boolean isCache, String tag) { volleyRequsest(Method.POST, url, hashMap, resultCallback,isCache, tag); } public void volleyGet(String url, final HashMap<String, String> hashMap, final ResultCallback resultCallback) { volleyGet(url, hashMap, resultCallback, null); } public void volleyGet(String url, final HashMap<String, String> hashMap, final ResultCallback resultCallback, String tag) { StringBuilder sb = new StringBuilder(url); if (hashMap != null) { sb.append("?"); for (String key : hashMap.keySet()) { sb.append(key); sb.append("="); sb.append(URLEncoder.encode(hashMap.get(key))); sb.append("&"); } sb.deleteCharAt(sb.length()-1); } volleyRequsest(Method.GET, sb.toString(), null, resultCallback, true, tag); } private void volleyRequsest(int method, String url, final HashMap<String, String> hashMap, final ResultCallback resultCallback, boolean isCache, String tag) { StringRequest mStringRequest = new StringRequest(method, url, new Response.Listener<String>() { @Override public void onResponse(String response) { resultCallback.onSuccess(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { resultCallback.onFailed(error); } }) { protected final String TYPE_UTF8_CHARSET = "charset=UTF-8"; // 重写parseNetworkResponse方法改变返回头参数解决乱码问题 // 主要是看服务器编码,如果服务器编码不是UTF-8的话那么就需要自己转换,反之则不需要 @Override protected Response<String> parseNetworkResponse( NetworkResponse response) { try { String type = response.headers.get(HTTP.CONTENT_TYPE); if (type == null) { type = TYPE_UTF8_CHARSET; response.headers.put(HTTP.CONTENT_TYPE, type); } else if (!type.contains("UTF-8")) { type += ";" + TYPE_UTF8_CHARSET; response.headers.put(HTTP.CONTENT_TYPE, type); } } catch (Exception e) { } return super.parseNetworkResponse(response); } // 携带参数 @Override protected HashMap<String, String> getParams() throws AuthFailureError { // HashMap<String , String> map = new HashMap<String, String>(); // for (String key : hashMap.keySet()) { // map.put(key,URLEncoder.encode(hashMap.get(key))); // } return hashMap; } // Volley请求类提供了一个 getHeaders()的方法,重载这个方法可以自定义HTTP 的头信息。(也可不实现) // public Map<String, String> getHeaders() throws AuthFailureError { // HashMap<String, String> headers = new HashMap<String, String>(); // headers.put("Content-Type", "charset=UTF-8"); // return headers; // } }; if (!TextUtils.isEmpty(tag)) { mStringRequest.setTag(tag); } mStringRequest.setShouldCache(isCache); mRequestQueue.add(mStringRequest); } }
手机端拍照选择相册功能类
package com.startimes.callhost.utils;
import android.app.Activity;import android.app.AlertDialog;import android.content.ActivityNotFoundException;import android.content.ContentResolver;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Matrix;import android.net.Uri;import android.provider.MediaStore;import android.util.Log;import android.view.ContextThemeWrapper;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.ListAdapter;import android.widget.Toast;import com.startimes.callhost.model.EaseConstant;import com.startimes.callhost.volley.CircleImage;
/*** 拍照工具类*/public class ImagePostUtil {
private static final int SELECT_PIC = 1001 ; // 拍照private static final int CANMERA = 1002 ; // 拍照
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;}
public static void doPickPhoto( final Activity context) {String[] choices={ "拍照" , "图库中选择" };ListAdapter adapter = new ArrayAdapter<String>(context, android.R.layout. simple_list_item_1 , choices);AlertDialog.Builder builder = new AlertDialog.Builder(context);builder.setSingleChoiceItems(adapter, - 1 ,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {dialog.dismiss();switch (which) {case 0 :takePicture ( context );break ;case 1 :selectImage ( context );break ;}}
});builder.create().show();}
/*** 从摄像头选择图片** @param context*/private static void takePicture( final Context context) {try {final Intent intent = new Intent(MediaStore. ACTION_IMAGE_CAPTURE ,null );intent.setAction(MediaStore. ACTION_IMAGE_CAPTURE );intent.putExtra(MediaStore. EXTRA_OUTPUT ,EaseConstant. getCameraIconUri ());((Activity) context).startActivityForResult(intent, CANMERA );} catch (ActivityNotFoundException e) {Toast. makeText (context, "打开摄像头异常" , Toast. LENGTH_SHORT ).show();}}
/*** 从图库选择图片** @param context*/private static void selectImage( final Context context) {try {final Intent intent = new Intent(Intent. ACTION_GET_CONTENT , null );intent.setType( "image/*" );intent.putExtra( "crop" , "true" );intent.putExtra( "aspectX" , 1 );intent.putExtra( "aspectY" , 1 );intent.putExtra( "outputX" , 600 );intent.putExtra( "outputY" , 600 );intent.putExtra( "scale" , true );intent.putExtra( "return-data" , false );intent.putExtra(MediaStore. EXTRA_OUTPUT ,EaseConstant. getIconUri ());intent.putExtra( "outputFormat" ,Bitmap.CompressFormat. JPEG .toString());
intent.putExtra( "noFaceDetection" , true ); // no face detection((Activity) context).startActivityForResult(intent, SELECT_PIC );} catch (ActivityNotFoundException e) {Toast. makeText (context, "未找到相册" , Toast. LENGTH_SHORT ).show();}}
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {// 源图片的高度和宽度final int height = options. outHeight ;final int width = options. outWidth ;int inSampleSize = 1 ;if (height > reqHeight || width > reqWidth) {// 计算出实际宽高和目标宽高的比率final int heightRatio = Math. round (( float ) height/ ( float ) reqHeight);final int widthRatio = Math. round (( float ) width / ( float ) reqWidth);// 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高// 一定都会大于等于目标的宽和高。inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;}return inSampleSize;}
public static void doAfterSelectUserIamege(Activity contect,int requestCode, int resultCode, Intent data, CircleImage imageView) {if (resultCode == Activity. RESULT_OK ) {try {Bitmap bitmap = null ;if (requestCode == SELECT_PIC ) {Uri uri = EaseConstant. getIconUri ();
Log. e ( "uri" , uri.toString());ContentResolver cr = contect.getContentResolver();BitmapFactory.Options options = new BitmapFactory.Options();options. inJustDecodeBounds = false ;bitmap = BitmapFactory. decodeStream (cr.openInputStream(uri), null , options);imageView.setLocalImageBitmap(bitmap);
// UserRequest.postUserImage();} else {cropImageUri (contect);}
} catch (Exception e) {Log. e ( "sai" , "error" , e);Toast. makeText (contect, "未选择图片" , Toast. LENGTH_SHORT ).show();}}}
private static void cropImageUri(Activity context) {
Intent intent = new Intent( "com.android.camera.action.CROP" );intent.setDataAndType(EaseConstant. getCameraIconUri (), "image/*" );intent.putExtra( "crop" , "true" );intent.putExtra( "aspectX" , 1 );intent.putExtra( "aspectY" , 1 );intent.putExtra( "outputX" , 600 );intent.putExtra( "outputY" , 600 );intent.putExtra( "scale" , true );intent.putExtra(MediaStore. EXTRA_OUTPUT , EaseConstant. getIconUri ());intent.putExtra( "return-data" , false );intent.putExtra( "outputFormat" , Bitmap.CompressFormat. JPEG .toString());intent.putExtra( "noFaceDetection" , true ); // no face detection
context.startActivityForResult(intent, SELECT_PIC );
}}
volley请求搭配图片请求
最新推荐文章于 2018-12-29 16:43:44 发布