Android 图片操作(Bitmap)


/**
	 * 将多个Bitmap合并成一个图片。
	 * 
	 * @param int 将多个图合成多少列
	 * @param Bitmap... 要合成的图片
	 * @return
	 */
public static Bitmap combineBitmaps(int columns, Bitmap... bitmaps) {
		if (columns <= 0 || bitmaps == null || bitmaps.length == 0) {
			throw new IllegalArgumentException("Wrong parameters: columns must > 0 and bitmaps.length must > 0.");
		}
		int maxWidthPerImage = 0;
		int maxHeightPerImage = 0;
		for (Bitmap b : bitmaps) {
			maxWidthPerImage = maxWidthPerImage > b.getWidth() ? maxWidthPerImage : b.getWidth();
			maxHeightPerImage = maxHeightPerImage > b.getHeight() ? maxHeightPerImage : b.getHeight();
		}
		int rows = 0;
		if (columns >= bitmaps.length) {
			rows = 1;
			columns = bitmaps.length;
		} else {
			rows = bitmaps.length % columns == 0 ? bitmaps.length / columns : bitmaps.length / columns + 1;
		}
		Bitmap newBitmap = Bitmap.createBitmap(columns * maxWidthPerImage, rows * maxHeightPerImage, Config.RGB_565);

		for (int x = 0; x < rows; x++) {
			for (int y = 0; y < columns; y++) {
				int index = x * columns + y;
				if (index >= bitmaps.length)
					break;
				newBitmap = mixtureBitmap(newBitmap, bitmaps[index], new PointF(y * maxWidthPerImage, x * maxHeightPerImage));
			}
		}
		return newBitmap;
	}


/**
	 * Mix two Bitmap as one.
	 * 
	 * @param bitmapOne
	 * @param bitmapTwo
	 * @param point
	 *            where the second bitmap is painted.
	 * @return
	 */
	public static Bitmap mixtureBitmap(Bitmap first, Bitmap second, PointF fromPoint) {
		if (first == null || second == null || fromPoint == null) {
			return null;
		}
		Bitmap newBitmap = Bitmap.createBitmap(first.getWidth(), first.getHeight(), Config.ARGB_4444);
		Canvas cv = new Canvas(newBitmap);
		cv.drawBitmap(first, 0, 0, null);
		cv.drawBitmap(second, fromPoint.x, fromPoint.y, null);
		cv.save(Canvas.ALL_SAVE_FLAG);
		cv.restore();
		return newBitmap;
	}


//截屏
public static Bitmap getScreenshotsForCurrentWindow(Activity activity) {
		View cv = activity.getWindow().getDecorView();
		Bitmap bmp = Bitmap.createBitmap(cv.getWidth(), cv.getHeight(), Bitmap.Config.ARGB_4444);
		cv.draw(new Canvas(bmp));
		return bmp;
	}


//旋转图片
// Rotates the bitmap by the specified degree.
// If a new bitmap is created, the original bitmap is recycled.
public static Bitmap rotate(Bitmap b, int degrees) {
	if (degrees != 0 && b != null) {
		Matrix m = new Matrix();
		m.setRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2);
		try {
			b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true);
			 if (b != b2) {
			 b.recycle();
			 b = b2;
			 }
		} catch (OutOfMemoryError ex) {
			// We have no memory to rotate. Return the original bitmap.
		}
	}
		return b;
}


//可用于生成缩略图。
/**
 * Creates a centered bitmap of the desired size. Recycles the input.
 * 
 * @param source
 */
public static Bitmap extractMiniThumb(Bitmap source, int width, int height) {
	return extractMiniThumb(source, width, height, true);
}

public static Bitmap extractMiniThumb(Bitmap source, int width, int height, boolean recycle) {
	if (source == null) {
		return null;
	}

	float scale;
	if (source.getWidth() < source.getHeight()) {
		scale = width / (float) source.getWidth();
	} else {
		scale = height / (float) source.getHeight();
	}
	Matrix matrix = new Matrix();
	matrix.setScale(scale, scale);
	Bitmap miniThumbnail = transform(matrix, source, width, height, false);

	if (recycle && miniThumbnail != source) {
		source.recycle();
	}
	return miniThumbnail;
}

public static Bitmap transform(Matrix scaler, Bitmap source, int targetWidth, int targetHeight, boolean scaleUp) {
		int deltaX = source.getWidth() - targetWidth;
		int deltaY = source.getHeight() - targetHeight;
		if (!scaleUp && (deltaX < 0 || deltaY < 0)) {
			/*
			 * In this case the bitmap is smaller, at least in one dimension,
			 * than the target. Transform it by placing as much of the image as
			 * possible into the target and leaving the top/bottom or left/right
			 * (or both) black.
			 */
			Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
			Canvas c = new Canvas(b2);

			int deltaXHalf = Math.max(0, deltaX / 2);
			int deltaYHalf = Math.max(0, deltaY / 2);
			Rect src = new Rect(deltaXHalf, deltaYHalf, deltaXHalf + Math.min(targetWidth, source.getWidth()), deltaYHalf
					+ Math.min(targetHeight, source.getHeight()));
			int dstX = (targetWidth - src.width()) / 2;
			int dstY = (targetHeight - src.height()) / 2;
			Rect dst = new Rect(dstX, dstY, targetWidth - dstX, targetHeight - dstY);
			c.drawBitmap(source, src, dst, null);
			return b2;
		}
		float bitmapWidthF = source.getWidth();
		float bitmapHeightF = source.getHeight();

		float bitmapAspect = bitmapWidthF / bitmapHeightF;
		float viewAspect = (float) targetWidth / targetHeight;

		if (bitmapAspect > viewAspect) {
			float scale = targetHeight / bitmapHeightF;
			if (scale < .9F || scale > 1F) {
				scaler.setScale(scale, scale);
			} else {
				scaler = null;
			}
		} else {
			float scale = targetWidth / bitmapWidthF;
			if (scale < .9F || scale > 1F) {
				scaler.setScale(scale, scale);
			} else {
				scaler = null;
			}
		}

		Bitmap b1;
		if (scaler != null) {
			// this is used for minithumb and crop, so we want to filter here.
			b1 = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), scaler, true);
		} else {
			b1 = source;
		}

		int dx1 = Math.max(0, b1.getWidth() - targetWidth);
		int dy1 = Math.max(0, b1.getHeight() - targetHeight);

		Bitmap b2 = Bitmap.createBitmap(b1, dx1 / 2, dy1 / 2, targetWidth, targetHeight);

		if (b1 != source) {
			b1.recycle();
		}

		return b2;
	}


//图片剪切
public static Bitmap cutBitmap(Bitmap mBitmap, Rect r, Bitmap.Config config) {
	int width = r.width();
	int height = r.height();

	Bitmap croppedImage = Bitmap.createBitmap(width, height, config);

	Canvas cvs = new Canvas(croppedImage);
	Rect dr = new Rect(0, 0, width, height);
	cvs.drawBitmap(mBitmap, r, dr, null);
	return croppedImage;
}


//从任一Drawable得到Bitmap
public static Bitmap drawableToBitmap(Drawable drawable) {
	Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.RGB_565);
	Canvas canvas = new Canvas(bitmap);
	drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
	drawable.draw(canvas);
	return bitmap;
}
//从任一Bitmap中得到Drawable
一、Bitmap转Drawable


Bitmap bm=xxx; //xxx根据你的情况获取

BitmapDrawable bd=new BitmapDrawable(bm);
因为BtimapDrawable是Drawable的子类,最终直接使用bd对象即可。

二、 Drawable转Bitmap

转成Bitmap对象后,可以将Drawable对象通过Android的SK库存成一个字节输出流,最终还可以保存成为jpg和png的文件。
Drawable d=xxx; //xxx根据自己的情况获取drawable

BitmapDrawable bd = (BitmapDrawable) d;

Bitmap bm = bd.getBitmap();
最终bm就是我们需要的Bitmap对象了。



// 从资源中获取Bitmap
public static Bitmap getBitmapFromResources(Activity act, int resId) {
Resources res = act.getResources();
return BitmapFactory.decodeResource(res, resId);
}

// byte[] → Bitmap
public static Bitmap convertBytes2Bimap(byte[] b) {
if (b.length == 0) {
return null;
}
return BitmapFactory.decodeByteArray(b, 0, b.length);
}

// Bitmap → byte[]
public static byte[] convertBitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}

// 1)Drawable → Bitmap
public static Bitmap convertDrawable2BitmapByCanvas(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
// canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}

// 2)Drawable → Bitmap
public static Bitmap convertDrawable2BitmapSimple(Drawable drawable){
BitmapDrawable bd = (BitmapDrawable) drawable;
return bd.getBitmap();
}

// Bitmap → Drawable
public static Drawable convertBitmap2Drawable(Bitmap bitmap) {
BitmapDrawable bd = new BitmapDrawable(bitmap);
// 因为BtimapDrawable是Drawable的子类,最终直接使用bd对象即可。
return bd;


/**
	 * Save Bitmap to a file.保存图片到SD卡。
	 * 
	 * @param bitmap
	 * @param file
	 * @return error message if the saving is failed. null if the saving is
	 *         successful.
	 * @throws IOException
	 */
	public static void saveBitmapToFile(Bitmap bitmap, String _file) throws IOException {
		BufferedOutputStream os = null;
		try {
			File file = new File(_file);
			// String _filePath_file.replace(File.separatorChar +
			// file.getName(), "");
			int end = _file.lastIndexOf(File.separator);
			String _filePath = _file.substring(0, end);
			File filePath = new File(_filePath);
			if (!filePath.exists()) {
				filePath.mkdirs();
			}
			file.createNewFile();
			os = new BufferedOutputStream(new FileOutputStream(file));
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					Log.e(TAG_ERROR, e.getMessage(), e);
				}
			}
		}
	}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值