-
Canvas图片合成
int border = 2; Bitmap resultBitmap = Bitmap.createBitmap(w - border * 3, h - border * 3, Bitmap.Config.ARGB_8888); //填充颜色 resultBitmap.eraseColor(Color.WHITE); Log.e("TAG", "w = " + w + "h = " + h); Canvas cv = new Canvas(resultBitmap); int pieceWidth = w / 3 + border; int pieceHeight = h / 3 + border; int w2 = 0; int h2 = 0; //在画布上将每个经过处理后的碎片重新绘制到画布上 for (int i = 0; i < desBitmaps.size(); i++) { w2 = pieceWidth * (i % 3); h2 = pieceHeight * (i / 3); Log.e("TAG", "w2 = " + w2 + "h2 = " + h2); cv.drawBitmap(desBitmaps.get(i), w2, h2, null); cv.save(); cv.restore(); }
-
Canvas图片分割
/**
* 图片 - 切成 piece * piece 块
*/
public static List<ImagePiece> splitImage(Bitmap bitmap, int piece) {
List<ImagePiece> imagePieces = new ArrayList<>();
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int pieceWidth = width / piece;
int pieceHeight = height / piece;
for (int i = 0; i < piece; i++) {
for (int j = 0; j < piece; j++) {
ImagePiece imagePiece = new ImagePiece();
int x = i * pieceWidth;
int y = j * pieceHeight;
imagePiece.setBitmap(Bitmap.createBitmap(bitmap, x, y,
pieceWidth, pieceHeight));
imagePieces.add(imagePiece);
}
}
return imagePieces;
}
- Android图片加载
/**
* decode bitmap from Path for available inSampleSize
*/
public static Bitmap decodeBitmapFromFilePath(String fileName, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(fileName, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(fileName, options);
}
/**
* Calculate the inSampleSize needed
*/
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
/**
* 保存bitmap到本地
*/
public static void saveBitmap(Bitmap bitmap, String path) {
String savePath;
File filePic;
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
savePath = path;
} else {
Log.e("TAG", "外部SD卡不可用");
return;
}
try {
filePic = new File(savePath + File.separator + System.currentTimeMillis() + ".jpg");
if (!filePic.exists()) {
filePic.getParentFile().mkdirs();
filePic.createNewFile();
}
FileOutputStream fos = new FileOutputStream(filePic);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}