android BitmapUtils

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.TextUtils;

public class BitmapUtils {

	/**
	 * 根据文件名,从Assets中取图片
	 * 
	 * @param context
	 * @param fileName
	 *            例如:game_bg.png
	 * @return
	 */
	public static Bitmap getBitmapFromAsset(Context context, String fileName) {
		Bitmap bmp = null;
		if (TextUtils.isEmpty(fileName)) {
			return null;
		}
		AssetManager asm = context.getAssets();
		if (asm == null) {
			return bmp;
		}
		InputStream is = null;
		try {
			is = asm.open(fileName);
			bmp = BitmapFactory.decodeStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bmp;
	}

	/**
	 * 根据路径,以流的形式,在sdcard中读取图片
	 * 
	 * @param filename
	 * @return
	 */
	public static Bitmap getBitmapFormSdcard(String filename) {
		if (TextUtils.isEmpty(filename)) {
			return null;
		}

		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeFile(filename);
		} catch (OutOfMemoryError e) {
			if (bitmap != null) {
				if (!bitmap.isRecycled()) {
					bitmap.recycle();
				}
				bitmap = null;
			}
		} catch (Exception e) {
			if (bitmap != null) {
				if (!bitmap.isRecycled()) {
					bitmap.recycle();
				}
				bitmap = null;
			}
		}
		return bitmap;
	}

	/**
	 * 根据URL下载图片
	 * 
	 * @param imageUrl
	 *            网络url地址
	 * @param connectTimeout
	 *            链接超时
	 * @param readTimeout
	 *            读取超时
	 * @return
	 */
	public static Bitmap downloadPic(String imageUrl, int connectTimeout,
			int readTimeout) {
		if (TextUtils.isEmpty(imageUrl)) {
			return null;
		}
		URL url = null;
		HttpURLConnection conn = null;
		InputStream is = null;
		Bitmap bitmap = null;
		try {

			url = new URL(imageUrl);
			conn = (HttpURLConnection) url.openConnection();
			//
			conn.setConnectTimeout(connectTimeout);
			//
			conn.setReadTimeout(readTimeout);
			conn.setDoInput(true);
			//
			conn.connect();
			is = conn.getInputStream();
			//
			bitmap = BitmapFactory.decodeStream(is);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					is = null;
				}
			}
		}
		return bitmap;
	}

	/**
	 * 更改bitmap的宽,高
	 * 
	 * @param bmp
	 * @param targetWidth
	 * @param targetHeight
	 * @return
	 */
	public static Bitmap resizeBitmap(Bitmap bmp, int targetWidth,
			int targetHeight) {

		if (bmp == null || bmp.isRecycled()) {
			return null;
		}
		Bitmap bmResult = null;
		try {
			// 原始图片宽度
			float width = bmp.getWidth();
			// 原始图片高度
			float height = bmp.getHeight();

			Matrix m1 = new Matrix();
			// 这里指的是目标区域(不是目标图片)
			m1.postScale(targetWidth / width, targetHeight / height);
			// 声明位图
			bmResult = Bitmap.createBitmap(bmp, 0, 0, (int) width,
					(int) height, m1, true);

		} catch (Exception e) {
			if (bmResult != null) {
				if (!bmResult.isRecycled()) {
					bmResult.recycle();
					bmResult = null;
				}
			}
			bmResult = bmp;
		}
		return bmResult;
	}

	/**
	 * 按某个比例缩放图片
	 * 
	 * @param bmp
	 * @param ratio
	 * @return
	 */
	public static Bitmap resizeBitmap(Bitmap bmp, float ratio) {

		if (bmp == null || bmp.isRecycled()) {
			return null;
		}
		Bitmap bmResult = null;

		try {
			// 图片宽度
			float width = bmp.getWidth();
			// 图片高度
			float height = bmp.getHeight();

			Matrix m1 = new Matrix();
			m1.postScale(ratio, ratio);
			// 声明位图
			bmResult = Bitmap.createBitmap(bmp, 0, 0, (int) width,
					(int) height, m1, true);

		} catch (Exception e) {
			if (bmResult != null) {
				if (!bmResult.isRecycled()) {
					bmResult.recycle();
					bmResult = null;
				}
			}
			bmResult = bmp;
		}

		return bmResult;
	}

	/**
	 * 将图片存入Sdcard中指定路径
	 * 
	 * @param bitmap
	 * @param path
	 * @return
	 */
	public static boolean saveBitmapToSdcard(Bitmap bitmap, String path) {
		if (bitmap == null || TextUtils.isEmpty(path)) {
			return false;
		}
		File file = null;
		FileOutputStream fos = null;
		try {
			file = new File(path);
			if (file.exists()) {
				file.delete();
			}
			//
			fos = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos);
			fos.flush();
			return true;
		} catch (Exception e) {
			//
		} finally {
			if (null != fos) {
				try {
					fos.close();
				} catch (Exception e) {
				}
			}
		}
		return false;
	}

	/**
	 * 处理头像(填充圆角)
	 * 
	 * @param bitmap
	 * @param roundPx
	 * @return
	 */
	public static Bitmap getCornerBitmap(Bitmap bitmap, float roundPx) {
		if (bitmap == null) {
			return null;
		}
		Bitmap output = null;

		try {
			output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
					Config.ARGB_8888);
			Canvas canvas = new Canvas(output);
			final Rect rect = new Rect(0, 0, bitmap.getWidth(),
					bitmap.getHeight());
			final RectF rectF = new RectF(rect);

			final Paint paint = new Paint();
			paint.setAntiAlias(true);
			canvas.drawARGB(0, 0, 0, 0);
			canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
			paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
			canvas.drawBitmap(bitmap, rect, rect, paint);

			return output;
		} catch (OutOfMemoryError e) {
			if (output != null) {
				if (!output.isRecycled()) {
					output.recycle();
					output = null;
				}
			}
			output = bitmap;
			//
			e.printStackTrace();

		}
		return null;
	}

	/**
	 * 镜像效果mirror
	 * 
	 * @param originalImage
	 * @return
	 */
	public static Bitmap getMirrorImage(Bitmap originalImage) {
		if (originalImage == null) {
			return null;
		}

		Bitmap bitmapWithReflection = null;
		try {

			final int reflectionGap = 2;
			int width = originalImage.getWidth();
			int height = originalImage.getHeight();

			Matrix matrix = new Matrix();

			matrix.preScale(1, -1);

			Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
					height / 2, width, height / 2, matrix, false);

			bitmapWithReflection = Bitmap.createBitmap(width,
					(height + height / 6), Config.ARGB_8888);

			Canvas canvas = new Canvas(bitmapWithReflection);

			canvas.drawBitmap(originalImage, 0, 0, null);

			canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

			Paint paint = new Paint();

			LinearGradient shader = new LinearGradient(0, height, 0,
					bitmapWithReflection.getHeight() + reflectionGap + 20,
					0xffffffff, 0x00ffffff, TileMode.MIRROR);

			paint.setShader(shader);
			paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));

			canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
					+ reflectionGap, paint);
		} catch (OutOfMemoryError e) {
			if (bitmapWithReflection != null) {
				if (!bitmapWithReflection.isRecycled()) {
					bitmapWithReflection.recycle();
					bitmapWithReflection = null;
				}
			}
			bitmapWithReflection = originalImage;
			//
			e.printStackTrace();

		}
		return bitmapWithReflection;
	}
/**
	 * Mosaic a bitmap
	 * @param srcBitmap 
	 * @param radius The pixel number of a block. such as width/16
	 * @param dstBitmap the width and height must be the same of srcBitmap
	 * @return {@link #SUCCESS} or {@value #OUT_OF_BOUNDS_EXCEPTION}
	 */
	public static boolean mosaic(final Bitmap srcBitmap, final int radius, Bitmap dstBitmap){
		try {
			Log.d(TAG, "mosaic srcBitmap = " + srcBitmap + ", radius = " + radius + ", dstBitmap = " + dstBitmap);
			int w = srcBitmap.getWidth();
			int h = srcBitmap.getHeight();
			int[] srcData = new int[w*h];
			int[] dstData = new int[w*h];
			int midRadius = radius >> 1;
			int srcX,srcY;
//			int[] srcData = srcBitmap.mBuffer;
			
			Log.d(TAG, "mosaic:w= " + w + ",h=" +h);
			long startTime  = System.currentTimeMillis();
			srcBitmap.getPixels(srcData, 0, w, 0, 0, w, h);
		
			for (int j = 0; j < h; j++) {
				for (int i = 0; i < w; i++) {
					srcX = i - i%radius + midRadius;
					srcY = j - j%radius + midRadius;
					if(srcX >= w){
						srcX = w-1;
					}
					if(srcY >= h){
						srcY = h-1;
					}					
					dstData[j*w + i] = srcData[srcY * w + srcX];
				}
			}	
			Log.d(TAG, "exe time = " + (System.currentTimeMillis() - startTime));
			dstBitmap.setPixels(dstData, 0, w, 0, 0, w, h);
			Log.d(TAG, "setPixels time = " + (System.currentTimeMillis() - startTime));
			
		} catch (ArrayIndexOutOfBoundsException e) {
			// TODO: handle exception
			Log.e(TAG, "ArrayIndexOutOfBoundsException = " + e);
			return false;
		}catch (IllegalStateException e) {
			Log.e(TAG, "IllegalStateException = " + e);
			return false;		
		}catch (Exception e) {
			Log.e(TAG, "Exception = " + e);
			return false;
		}
		
		return true;
	}
	
	
	/**
	 * Mosaic2 a bitmap. The time cost is 9 times against as mosaic(...), 
	 * but the memory is half of it
	 * @param srcBitmap 
	 * @param radius The pixel number of a block. such as width/16
	 * @param dstBitmap the width and height must be the same of srcBitmap
	 * @return {@link #SUCCESS} or {@value #OUT_OF_BOUNDS_EXCEPTION}
	 */
	public static boolean mosaic2(final Bitmap srcBitmap, final int radius, Bitmap dstBitmap){
		try {
			Log.d(TAG, "mosaic srcBitmap = " + srcBitmap + ", radius = " + radius + ", dstBitmap = " + dstBitmap);
			int w = srcBitmap.getWidth();
			int h = srcBitmap.getHeight();
			int srcData = 0;
//			int dstData = 0;
			int midRadius = radius >> 1;
			int srcX,srcY;
			
			Log.d(TAG, "mosaic:w= " + w + ",h=" +h);
			long startTime  = System.currentTimeMillis();
//			srcBitmap.getPixels(srcData, 0, w, 0, 0, w, h);
			
		
			for (int j = 0; j < h; j++) {
				for (int i = 0; i < w; i++) {
					srcX = i - i%radius + midRadius;
					srcY = j - j%radius + midRadius;
					if(srcX >= w){
						srcX = w-1;
					}
					if(srcY >= h){
						srcY = h-1;
					}	
					srcData = srcBitmap.getPixel(srcX, srcY);
					dstBitmap.setPixel(i, j, srcData);
//					dstData[j*w + i] = srcData[srcY * w + srcX];
				}
			}	
			Log.d(TAG, "exe time = " + (System.currentTimeMillis() - startTime));
//			dstBitmap.setPixels(dstData, 0, w, 0, 0, w, h);
//			Log.d(TAG, "setPixels time = " + (System.currentTimeMillis() - startTime));
			
		} catch (ArrayIndexOutOfBoundsException e) {
			// TODO: handle exception
			Log.e(TAG, "ArrayIndexOutOfBoundsException = " + e);
			return false;
		}catch (IllegalStateException e) {
			Log.e(TAG, "IllegalStateException = " + e);
			return false;		
		}catch (Exception e) {
			Log.e(TAG, "Exception = " + e);
			return false;
		}
		
		return true;
	}

    /**
     * 设置 ImageView 图标颜色
     */
    public void setImageViewColorFilter(ImageView view, int color) {
        if (view == null)
            return;
        view.setColorFilter(view.getContext().getResources().getColor(color));
    }

    /**
     * 获取 指定颜色 的图标
     *
     * @param context
     * @param resID
     * @return
     */
    public Drawable getThemeDrawableColorFilter(Context context, int resID, int color) {
        Drawable drawable = null;
        try {
            drawable = context.getResources().getDrawable(resID);
            drawable.setColorFilter(context.getResources().getColor(color), PorterDuff.Mode.SRC_ATOP);
        } catch (Exception | OutOfMemoryError error) {
            error.printStackTrace();
        }
        if (drawable == null) {
            return new ColorDrawable(Color.TRANSPARENT);
        } else {
            return drawable;
        }
    }

}

你可能感兴趣的:(Android代码)