盒子
盒子
文章目录
  1. ImageView
  2. Bitmap
    1. 本地图片选择
    2. 图片加载
    3. 格式转换
    4. 图片拉伸
    5. 图片比例缩放 / 质量压缩
    6. 图片裁剪
    7. 图片旋转 / 偏移
  3. 图片编辑
  4. 图片识别
    1. 二维码

图片

ImageView

byte[] photoBytes;  // 二进制图片内存数据
ImageView imageView =this.findViewById(R.id.imageViewPhoto);
Bitmap bitmap = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
imageView.setImageBitmap(bitmap);

// ImageLayout
bmp = base64ToBitmap(strBase64);
ImageView iv = new ImageView(this);
iv.setImageBitmap(bmp);
mImageLayout.addView(iv, new LinearLayout.LayoutParams(300, 300));

Bitmap

本地图片选择

    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, 0);

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);

// 该模式要求
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, 0);
// 接收

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (data == null || data.getData() == null) {
ToastUtil.show(this, "无效图片");
return;
}
try {
Log.e(TAG, "onActivityResult: " + data.getData());
mBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
return;
}
if (mBitmap == null) {
ToastUtil.show(this, "图片加载失败");
return;
}
ToastUtil.show(this, "图片加载成功");
Glide.with(this)
.load(mBitmap)
.into(ivShow); // ImageView
}
}
// uri -> 真实路径
public String getRealPathFromURI(Uri contentUri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if(cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}

图片加载

  • implementation 'com.github.bumptech.glide:glide:4.10.0'
// base64 图片数据
static Bitmap base64ToBitmap(String base64Data) {
byte[] bytes = Base64Utils.decode(base64Data, Base64Utils.NO_WRAP);
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}

/**
* 解析图片的旋转方向
*
* @param path 图片的路径
* @return 旋转角度
*/
public static final int ROTATE0 = 0;
public static final int ROTATE90 = 90;
public static final int ROTATE180 = 180;
public static final int ROTATE270 = 270;
public static int decodeImageDegree(String path) {
int degree = ROTATE0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation =
exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = ROTATE90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = ROTATE180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = ROTATE270;
break;
default:
degree = ROTATE0;
break;
}
} catch (Exception e) {
e.printStackTrace();
degree = ROTATE0;
}
return degree;
}
public static int decodeImageDegree(byte[] jpeg) {
int degree = ImageExif.getOrientation(jpeg);
return degree;
}
/**
* 从文件中加载图片数据
*
* @param path 图片的本地存储路径
* @return Bitmap 图片数据
*/
public static Bitmap loadBitmapFromFile(String path) {
Bitmap bitmap = null;
if (path != null) {
try {
bitmap = BitmapFactory.decodeFile(path);
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return bitmap;
}

/**
* 根据从数据中读到的方向旋转图片
*
* @param orientation 图片方向
* @param bitmap 要旋转的bitmap
* @return 旋转后的图片
*/
public static Bitmap rotateBitmap(float orientation, Bitmap bitmap) {
Bitmap transformed;
Matrix m = new Matrix();
if (orientation == 0) {
transformed = bitmap;
} else {
m.setRotate(orientation);
transformed = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
}
return transformed;
}

格式转换

/**
* @param bitmap 图片
* @param quality 生成的JPG的质量
* @param maxSize 最大边像素数
* @return base64编码的数据
*/
public static String bitmapToJpegBase64(Bitmap bitmap, int quality, float maxSize) {
try {
float scale = maxSize / Math.max(bitmap.getWidth(), bitmap.getHeight());
if (scale < 1) {
bitmap = scale(bitmap, scale);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, quality, out);
byte[] data = out.toByteArray();
out.close();

return Base64Utils.encodeToString(data, Base64Utils.NO_WRAP);
} catch (Exception e) {
return null;
}
}

图片拉伸

/**
* 等比压缩图片
*
* @param bitmap 原图
* @param scale 压缩因子
* @return 压缩后的图片
*/
private static Bitmap scale(Bitmap bitmap, float scale) {
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
/**
* 尺寸缩放
*
* @param bitmap bitmap
* @param w width
* @param h height
* @return scaleBitmap
*/
public static Bitmap scale(Bitmap bitmap, int w, int h) {
if (bitmap == null) {
return null;
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) w / width);
float scaleHeight = ((float) h / height);
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
}
/**
* 等比压缩图片
*
* @param resBitmap 原图
* @param desWidth 压缩后图片的宽度
* @param desHeight 压缩后图片的高度
* @return 压缩后的图片
*/
public static Bitmap calculateInSampleSize(Bitmap resBitmap, int desWidth, int desHeight) {
int resWidth = resBitmap.getWidth();
int resHeight = resBitmap.getHeight();
if (resHeight > desHeight || resWidth > desWidth) {
// 计算出实际宽高和目标宽高的比率
final float heightRatio = (float) desHeight / (float) resHeight;
final float widthRatio = (float) desWidth / (float) resWidth;
float scale = heightRatio < widthRatio ? heightRatio : widthRatio;
return scale(resBitmap, scale);
}
return resBitmap;
}

图片比例缩放 / 质量压缩

/**
* 等比压缩图片
*
* @param bitmap 原图
* @param scale 压缩因子
* @return 压缩后的图片
*/
private static Bitmap scale(Bitmap bitmap, float scale) {
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}

/**
* 质量压缩
* @param bitmap 被压缩的图片
* @param sizeLimit 大小限制
* @return 压缩后的图片
*/
private Bitmap compressBitmap(Bitmap bitmap, long sizeLimit) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);

// 循环判断压缩后图片是否超过限制大小
while(baos.toByteArray().length / 1024 > sizeLimit) {
// 清空baos
baos.reset();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
quality -= 10;
}

Bitmap newBitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, null);

return newBitmap;
}
// 将色彩模式换成RGB_565也会比默认的ARGB8888降低一半质量
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
bm = BitmapFactory.decodeFile(filePath, options);

// 质量压缩:百度
/**
* @param bitmap 图片
* @param quality 生成的JPG的质量
* @param maxSize 最大边像素数
* @return base64编码的数据
*/
public static String bitmapToJpegBase64(Bitmap bitmap, int quality, float maxSize) {
try {
float scale = maxSize / Math.max(bitmap.getWidth(), bitmap.getHeight());
if (scale < 1) {
bitmap = scale(bitmap, scale);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, quality, out);
byte[] data = out.toByteArray();
out.close();

return Base64Utils.encodeToString(data, Base64Utils.NO_WRAP);
} catch (Exception e) {
return null;
}
}

图片裁剪

/**
* 裁剪
*
* @param bitmap 原图
* @return 裁剪后的图像
*/
private Bitmap cropBitmap(Bitmap bitmap) {
int w = bitmap.getWidth(); // 得到图片的宽,高
int h = bitmap.getHeight();
int cropWidth = w >= h ? h : w;// 裁切后所取的正方形区域边长
cropWidth /= 2;
int cropHeight = (int) (cropWidth / 1.2);
return Bitmap.createBitmap(bitmap, w / 3, 0, cropWidth, cropHeight, null, false);
}

图片旋转 / 偏移

/**
* 选择变换
*
* @param origin 原图
* @param alpha 旋转角度,可正可负
* @return 旋转后的图片
*/
private Bitmap rotateBitmap(Bitmap origin, float alpha) {
if (origin == null) {
return null;
}
int width = origin.getWidth();
int height = origin.getHeight();
Matrix matrix = new Matrix();
matrix.setRotate(alpha);
// 围绕原地进行旋转
Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
if (newBM.equals(origin)) {
return newBM;
}
origin.recycle();
return newBM;
}

/**
* 偏移效果
* @param origin 原图
* @return 偏移后的bitmap
*/
private Bitmap skewBitmap(Bitmap origin) {
if (origin == null) {
return null;
}
int width = origin.getWidth();
int height = origin.getHeight();
Matrix matrix = new Matrix();
matrix.postSkew(-0.6f, -0.3f);
Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
if (newBM.equals(origin)) {
return newBM;
}
origin.recycle();
return newBM;
}

图片编辑

  • Imaging
    • 图片编辑库,缩放,涂鸦,文字,马赛克,裁剪,旋转灯

图片识别

[视频]

二维码

// implementation 'com.google.zxing:core:3.3.3'
package com.es.util;

import android.graphics.Bitmap;
import android.text.TextUtils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.util.Hashtable;

public class QrCodeUtil {
/**
* 生成简单二维码: createQRCodeBitmap(content, 200, 200,"UTF-8","H", "1", Color.BLACK, Color.WHITE);
*
* @param content 字符串内容
* @param width 二维码宽度
* @param height 二维码高度
* @param character_set 编码方式(一般使用UTF-8)
* @param error_correction_level 容错率 L:7% M:15% Q:25% H:35%
* @param margin 空白边距(二维码与边框的空白区域)
* @param color_black 黑色色块
* @param color_white 白色色块
* @return BitMap
*/
public static Bitmap createQRCodeBitmap(String content, int width,int height,
String character_set,String error_correction_level,
String margin,int color_black, int color_white) {
// 字符串内容判空
if (TextUtils.isEmpty(content)) {
return null;
}
// 宽和高>=0
if (width < 0 || height < 0) {
return null;
}
try {
/** 1.设置二维码相关配置 */
Hashtable<EncodeHintType, String> hints = new Hashtable<>();
// 字符转码格式设置
if (!TextUtils.isEmpty(character_set)) {
hints.put(EncodeHintType.CHARACTER_SET, character_set);
}
// 容错率设置
if (!TextUtils.isEmpty(error_correction_level)) {
hints.put(EncodeHintType.ERROR_CORRECTION, error_correction_level);
}
// 空白边距设置
if (!TextUtils.isEmpty(margin)) {
hints.put(EncodeHintType.MARGIN, margin);
}
/** 2.将配置参数传入到QRCodeWriter的encode方法生成BitMatrix(位矩阵)对象 */
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

/** 3.创建像素数组,并根据BitMatrix(位矩阵)对象为数组元素赋颜色值 */
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
//bitMatrix.get(x,y)方法返回true是黑色色块,false是白色色块
if (bitMatrix.get(x, y)) {
pixels[y * width + x] = color_black;//黑色色块像素设置
} else {
pixels[y * width + x] = color_white;// 白色色块像素设置
}
}
}
/** 4.创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,并返回Bitmap对象 */
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
return null;
}
}
}
支持一下
扫一扫,支持一下
  • 微信扫一扫
  • 支付宝扫一扫