ImageUtil.java 16 KB
Newer Older
tangguangrui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
package cn.dankal.base.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * Created by yangna on 14-5-6.
 */
public class ImageUtil {

	/**
	 * @param options
	 * @param reqWidth
	 * @return
	 */
	private static int calculateInWidthSize(BitmapFactory.Options options,
											int reqWidth) {
		// 婧愬浘鐗囩殑瀹藉害
		final int width = options.outWidth;
		int inSampleSize = 1;
		if (width > reqWidth) {
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = widthRatio;
		}
		return inSampleSize;
	}

	/**
	 * 如果最大值没有超过 max 原比例输出
	 *
	 * @param options
	 * @param max
	 * @return
	 */
	private static int calculateRatio(BitmapFactory.Options options, int max) {
		final int width = options.outWidth;
		final int height = options.outHeight;
		int inSampleSize = 1;

		if (width > max || height > max) {

			if (width >= height) {
				final int widthRatio = Math.round((float) width / (float) max);
				inSampleSize = widthRatio;
			} else {
				final int heightRatio = Math
						.round((float) height / (float) max);
				inSampleSize = heightRatio;
			}
		}
		return inSampleSize;
	}

	/**
	 * 按宽度等比缩放,reqWidth <= 0 图片不缩放
	 *
	 * @param pathName
	 * @param reqWidth
	 * @return
	 */
	@Deprecated
	public static Bitmap decodeBitmapWidthFromResource(String pathName,
                                                       int reqWidth) {
		if (reqWidth > 0) {
			// 绗竴娆¤В鏋愬皢inJustDecodeBounds璁剧疆涓簍rue锛屾潵鑾峰彇鍥剧墖澶у皬
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(pathName, options);
			// 璋冪敤涓婇潰瀹氫箟鐨勬柟娉曡绠梚nSampleSize鍊?
			options.inSampleSize = calculateInWidthSize(options, reqWidth);
			// 浣跨敤鑾峰彇鍒扮殑inSampleSize鍊煎啀娆¤В鏋愬浘鐗?
			options.inJustDecodeBounds = false;
			return BitmapFactory.decodeFile(pathName, options);
		} else {
			return BitmapFactory.decodeFile(pathName);
		}
	}

	/**
	 * 按最大值等比缩放,如果高或宽没有超过最大值按原图显示
	 *
	 * @param pathName
	 * @param max
	 * @return
	 */
	public static Bitmap decodeBitmapFromResource(String pathName, int max) {
		if (max > 0) {
			// 绗竴娆¤В鏋愬皢inJustDecodeBounds璁剧疆涓簍rue锛屾潵鑾峰彇鍥剧墖澶у皬
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(pathName, options);
			// 璋冪敤涓婇潰瀹氫箟鐨勬柟娉曡绠梚nSampleSize鍊?
			options.inSampleSize = calculateRatio(options, max);
			// 浣跨敤鑾峰彇鍒扮殑inSampleSize鍊煎啀娆¤В鏋愬浘鐗?
			options.inJustDecodeBounds = false;
			return BitmapFactory.decodeFile(pathName, options);
		} else {
			return BitmapFactory.decodeFile(pathName);
		}
	}

	/**
	 * 创建缩略图
	 *
	 * @param src
	 * @param width
	 * @param height
	 * @return
	 */
	public static Bitmap createScaleBitmap(Bitmap src, int width, int height) {
		Matrix m = new Matrix();

		int srcWidth = src.getWidth();
		int srcHeight = src.getHeight();

		float scale = 1;
		// 绔栧浘
		if (srcWidth > srcHeight) {
			scale = width / (float) srcWidth;
		} else {
			scale = height / (float) srcHeight;
		}

		m.postScale(scale, scale);

		Bitmap bitmap = Bitmap.createBitmap(src, 0, 0, src.getWidth(),
				src.getHeight(), m, true);

		src.recycle();

		return bitmap;
	}

	/**
	 * 创建缩略图,先拿原图,再创建新图
	 *
	 * @param srcPath
	 * @param max
	 * @return
	 */
	public static Bitmap getScaleImage(String srcPath, int max) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		newOpts.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(srcPath, newOpts);

		newOpts.inJustDecodeBounds = false;
		float w = newOpts.outWidth;
		float h = newOpts.outHeight;

		int be = 1;// be=1琛ㄧず涓嶇缉鏀?
		int scale = (int) (Math.max(w, h) / (float) max);

		if (scale > 1) {
			be = scale;
		}
		newOpts.inSampleSize = be;// 璁剧疆缂╂斁姣斾緥
		try {
			return BitmapFactory.decodeStream(new FileInputStream(srcPath),
					null, newOpts);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 创建缩略图
	 *
	 * @param src
	 * @param max
	 * @return
	 */
	public static Bitmap createScaleBitmap(Bitmap src, int max) {
		Matrix m = new Matrix();

		int srcWidth = src.getWidth();
		int srcHeight = src.getHeight();

		float scale = (max / (float) (Math.max(srcWidth, srcHeight)));
		m.postScale(scale, scale);

		Bitmap bitmap = Bitmap.createBitmap(src, 0, 0, src.getWidth(),
				src.getHeight(), m, true);

		return bitmap;
	}

	/**
	 *
	 * 裁剪图片意图
	 *
	 * @param activity
	 * @param uri
	 * @param outputX
	 * @param outputY
	 * @param requestCode
	 */
	public static void cropImage(Activity activity, Uri uri, int outputX,
                                 int outputY, int requestCode) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");

		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);

		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);

		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);
		intent.putExtra("return-data", true);
		activity.startActivityForResult(intent, requestCode);
	}

	/**
	 * 姘村钩鏂瑰悜妯$硦搴?
	 */
	private static float hRadius = 10;
	/**
	 *
	 */
	private static float vRadius = 10;
	/**
	 * 模糊迭代度
	 */
	private static int iterations = 7;

	/**
	 * 高斯模糊
	 */
	public static Drawable BoxBlurFilter(Bitmap bmp) {
		int width = bmp.getWidth();
		int height = bmp.getHeight();
		int[] inPixels = new int[width * height];
		int[] outPixels = new int[width * height];
		Bitmap bitmap = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_4444);
		bmp.getPixels(inPixels, 0, width, 0, 0, width, height);
		for (int i = 0; i < iterations; i++) {
			blur(inPixels, outPixels, width, height, hRadius);
			blur(outPixels, inPixels, height, width, vRadius);
		}
		blurFractional(inPixels, outPixels, width, height, hRadius);
		blurFractional(outPixels, inPixels, height, width, vRadius);
		bitmap.setPixels(inPixels, 0, width, 0, 0, width, height);
		Drawable drawable = new BitmapDrawable(null, bitmap);
		return drawable;
	}

	static void blur(int[] in, int[] out, int width, int height, float radius) {
		int widthMinus1 = width - 1;
		int r = (int) radius;
		int tableSize = 2 * r + 1;
		int divide[] = new int[256 * tableSize];

		for (int i = 0; i < 256 * tableSize; i++)
			divide[i] = i / tableSize;

		int inIndex = 0;

		for (int y = 0; y < height; y++) {
			int outIndex = y;
			int ta = 0, tr = 0, tg = 0, tb = 0;

			for (int i = -r; i <= r; i++) {
				int rgb = in[inIndex + clamp(i, 0, width - 1)];
				ta += (rgb >> 24) & 0xff;
				tr += (rgb >> 16) & 0xff;
				tg += (rgb >> 8) & 0xff;
				tb += rgb & 0xff;
			}

			for (int x = 0; x < width; x++) {
				out[outIndex] = (divide[ta] << 24) | (divide[tr] << 16)
						| (divide[tg] << 8) | divide[tb];

				int i1 = x + r + 1;
				if (i1 > widthMinus1)
					i1 = widthMinus1;
				int i2 = x - r;
				if (i2 < 0)
					i2 = 0;
				int rgb1 = in[inIndex + i1];
				int rgb2 = in[inIndex + i2];

				ta += ((rgb1 >> 24) & 0xff) - ((rgb2 >> 24) & 0xff);
				tr += ((rgb1 & 0xff0000) - (rgb2 & 0xff0000)) >> 16;
				tg += ((rgb1 & 0xff00) - (rgb2 & 0xff00)) >> 8;
				tb += (rgb1 & 0xff) - (rgb2 & 0xff);
				outIndex += height;
			}
			inIndex += width;
		}
	}

	static void blurFractional(int[] in, int[] out, int width, int height,
							   float radius) {
		radius -= (int) radius;
		float f = 1.0f / (1 + 2 * radius);
		int inIndex = 0;

		for (int y = 0; y < height; y++) {
			int outIndex = y;

			out[outIndex] = in[0];
			outIndex += height;
			for (int x = 1; x < width - 1; x++) {
				int i = inIndex + x;
				int rgb1 = in[i - 1];
				int rgb2 = in[i];
				int rgb3 = in[i + 1];

				int a1 = (rgb1 >> 24) & 0xff;
				int r1 = (rgb1 >> 16) & 0xff;
				int g1 = (rgb1 >> 8) & 0xff;
				int b1 = rgb1 & 0xff;
				int a2 = (rgb2 >> 24) & 0xff;
				int r2 = (rgb2 >> 16) & 0xff;
				int g2 = (rgb2 >> 8) & 0xff;
				int b2 = rgb2 & 0xff;
				int a3 = (rgb3 >> 24) & 0xff;
				int r3 = (rgb3 >> 16) & 0xff;
				int g3 = (rgb3 >> 8) & 0xff;
				int b3 = rgb3 & 0xff;
				a1 = a2 + (int) ((a1 + a3) * radius);
				r1 = r2 + (int) ((r1 + r3) * radius);
				g1 = g2 + (int) ((g1 + g3) * radius);
				b1 = b2 + (int) ((b1 + b3) * radius);
				a1 *= f;
				r1 *= f;
				g1 *= f;
				b1 *= f;
				out[outIndex] = (a1 << 24) | (r1 << 16) | (g1 << 8) | b1;
				outIndex += height;
			}
			out[outIndex] = in[width - 1];
			inIndex += width;
		}
	}

	static int clamp(int x, int a, int b) {
		return (x < a) ? a : (x > b) ? b : x;
	}

	/**
	 * 鍒涘缓甯︽湁瑙掓爣鏁板瓧鐨勫渾褰?
	 *
	 * @param context
	 * @param num
	 * @param bgColor
	 *            getResources().getColor(R.color.bg_red);
	 * @return
	 */
	public static Drawable createCircleFlag(Context context, String num,
                                            int bgColor) {
		int textSize = UIUtil.sp2px(context, 25);
		int r = textSize;

		// 鏂板缓涓?涓柊鐨勮緭鍑哄浘鐗?
		Bitmap output = Bitmap.createBitmap(2 * r, 2 * r,
				Bitmap.Config.ARGB_4444);
		Canvas canvas = new Canvas(output);

		// 鍒涘缓鍦?
		Paint paint = new Paint(Paint.FAKE_BOLD_TEXT_FLAG
				| Paint.ANTI_ALIAS_FLAG);
		paint.setColor(bgColor);
		paint.setAntiAlias(true);
		canvas.drawColor(Color.TRANSPARENT);
		canvas.drawCircle(r, r, r, paint);

		// 鍐欏瓧
		paint.setTextSize(textSize);
		paint.setColor(Color.WHITE);
		paint.setTextAlign(Paint.Align.CENTER);

		Paint.FontMetrics fontMetrics = paint.getFontMetrics();
		int h = (int) (fontMetrics.bottom - fontMetrics.top) / 4;

		canvas.drawText(num, r, r + h, paint);
		Drawable dr = new BitmapDrawable(null, output);
		dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());
		return dr;
	}

	/**
	 * 清除imageView
	 *
	 * @param mImageView
	 */
	public static void clearImageCache(ImageView mImageView) {
		try {
			BitmapDrawable bd = ((BitmapDrawable) mImageView.getDrawable());
			if (bd != null) {
				mImageView.setImageDrawable(null);
				Bitmap bitmap = bd.getBitmap();
				if (bitmap != null && !bitmap.isRecycled()) {
					bitmap.recycle();
				}
			}
		} catch (ClassCastException e) {

		}
	}

	/**
	 * we need to recyle bitmap.
	 *
	 * @param o
	 */
	public static void clearBitmap(Object o) {

		if (o instanceof View) {
			if (o instanceof ImageView) {
				ImageView recyleView = (ImageView) o;
				clearImageCache(recyleView);
			}
		}

		if (o instanceof ViewGroup) {
			ViewGroup group = (ViewGroup) o;
			for (int i = 0; i < group.getChildCount(); i++) {
				clearBitmap(group.getChildAt(i));
			}
		}
	}


	/**
	 * 读取图片的旋转的角度
	 *
	 * @param path
	 *            图片绝对路径
	 * @return 图片的旋转角度
	 */
	public static int getBitmapDegree(String path) {
		int degree = 0;
		try {
			// 从指定路径下读取图片,并获取其EXIF信息
			ExifInterface exifInterface = new ExifInterface(path);
			// 获取图片的旋转信息
			int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
				case ExifInterface.ORIENTATION_ROTATE_90:
					degree = 90;
					break;
				case ExifInterface.ORIENTATION_ROTATE_180:
					degree = 180;
					break;
				case ExifInterface.ORIENTATION_ROTATE_270:
					degree = 270;
					break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	/**
	 * 将图片按照某个角度进行旋转
	 *
	 * @param bm
	 *            需要旋转的图片
	 * @param degree
	 *            旋转角度
	 * @return 旋转后的图片
	 */
	public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
		Bitmap returnBm = null;

		// 根据旋转角度,生成旋转矩阵
		Matrix matrix = new Matrix();
		matrix.postRotate(degree);
		try {
			// 将原始图片按照旋转矩阵进行旋转,并得到新的图片
			returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
		} catch (OutOfMemoryError e) {
		}
		if (returnBm == null) {
			returnBm = bm;
		}
		if (bm != returnBm) {
			bm.recycle();
		}
		return returnBm;
	}

	/**
	 * 转换图片成圆形
	 *
	 * @param bitmap 传入Bitmap对象
	 * @return
	 */
	public static Bitmap toRoundBitmap(Bitmap bitmap) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float roundPx;
		float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
		if (width <= height) {
			roundPx = width / 2;
			top = 0;
			bottom = width;
			left = 0;
			right = width;
			height = width;
			dst_left = 0;
			dst_top = 0;
			dst_right = width;
			dst_bottom = width;
		} else {
			roundPx = height / 2;
			float clip = (width - height) / 2;
			left = clip;
			right = width - clip;
			top = 0;
			bottom = height;
			width = height;
			dst_left = 0;
			dst_top = 0;
			dst_right = height;
			dst_bottom = height;
		}

		Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect src = new Rect((int) left, (int) top, (int) right,
				(int) bottom);
		final Rect dst = new Rect((int) dst_left, (int) dst_top,
				(int) dst_right, (int) dst_bottom);
		final RectF rectF = new RectF(dst);

		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, src, dst, paint);
		return output;
	}


	/**
	 * 缩放Bitmap图片
	 **/
	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 String saveImageToFile(Bitmap bmp) throws Exception {
		//生成路径
		String root = Environment.getExternalStorageDirectory().getAbsolutePath();
		root = Environment.getDataDirectory().getAbsolutePath() + "/data/cn.runworld.mctower.visitor/";
		String dirName = "erweima16";
		File appDir = new File(root , dirName);
		if (!appDir.exists()) {
			appDir.mkdirs();
		}

		LogUtils.e("aa","path = "+appDir.getAbsolutePath());

		//文件名为时间
		long timeStamp = System.currentTimeMillis();
		String fileName = timeStamp + ".jpg";

		//获取文件
		File file = new File(appDir, fileName);
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			return file.getAbsolutePath();
		} catch (FileNotFoundException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				throw e;
			}
		}
	}

}