工作中用到图片翻转功能,是基于百度上找到的算法。
做了些许修改,入参和出参都是图片的byte数组,区分了JPG和PNG
可以水平翻转和垂直翻转,对于白底图(一般是PNG格式)翻转时可以防止背景变黑色
/**
* 上下或左右翻转图片
*
* @param urlStr 主图的地址,主要用于区分格式
* @param reverseType 翻转类型
* @param data 图片二进制数据,根据urlStr网络获取到的
* @return 翻转后的图片二进制数据
*/
public byte[] reverseImage(String urlStr, String reverseType, byte[] data) throws Exception {
ByteArrayInputStream in = null;
ByteArrayOutputStream os = null;
BufferedImage bi = null;
BufferedImage newImg = null;
try {
//这种会HeadLess的Exception,由于暂时无法解决,所以直接抛弃使用了
// Image imageTookit = Toolkit.getDefaultToolkit().createImage(data);
//以下操作需要区分PNG和JPG,JPG和PNG都有可能因为不支持的操作而会变红
// 创建输入流
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
// byte[] -> BufferedImage
bi = ImageIO.read(byteArrayInputStream);
String picType ="jpg";
if(urlStr.endsWith("png")){
picType="png";
}
// 关流
byteArrayInputStream.close();
int width = bi.getWidth();
int height = bi.getHeight();
double[] matrix;
if ("updown".equals(reverseType)) {
matrix = new double[]{1, 0, 0, -1, 0, height};
} else {
matrix = new double[]{-1, 0, 0, 1, width, 0};
}
AffineTransform affineTransform = new AffineTransform(matrix);
//设置透明start
newImg = new BufferedImage(width, height,bi.getType());
Graphics2D g = newImg.createGraphics();
if("png".equals(picType)) {
//png才可以设置透明背景,其他格式可能会变红
newImg = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g.dispose();
g=newImg.createGraphics();
}
//设置透明end
//设置翻转start
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawRenderedImage(bi, affineTransform);
g.dispose();
//设置翻转end
os = new ByteArrayOutputStream();
ImageIO.write(newImg, picType, os);
if (os != null) {
data = os.toByteArray();
}
} catch (Exception e) {
//TODO:捕获异常
} finally {
//TODO:关闭资源
}
return data;
}
//这里顺便给出我获取data的逻辑
/**
* 根据图片地址获取图片的二进制数据
*
* @param imgUrl
* @return
*/
public static byte[] getByteResponse(String imgUrl) {
byte[] data = null;
InputStream inStream = null;
try {
if (StringUtils.isBlank(imgUrl)) {
System.err.println("图片路径为空");
return null;
}
URL url = new URL(imgUrl); // 打开链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); // 设置请求方式为"GET"
conn.setConnectTimeout(5 * 1000); // 超时响应时间为5秒
inStream = conn.getInputStream(); // 通过输入流获取图片数据
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (inStream != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // 创建一个Buffer字符串
int len = 0; // 每次读取的字符串长度,如果为-1,代表全部读取完毕
try {
while ((len = inStream.read(buffer)) != -1) { // 使用一个输入流从buffer里把数据读取出来
outStream.write(buffer, 0, len); // 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
}
} catch (IOException e) {
return null;
}
// 关闭输入流
try {
inStream.close();
} catch (IOException e) {
return null;
}
data = outStream.toByteArray();
if(data==null){
System.err.println("图片返回为空");
}else{
return data;
}
}
return null;
}