整理图片效果处理(整合)
一、java 图片颜色处理(如替换背景颜色)
package test;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
public class PictureTreal {
public static void main(String args[]) throws IOException {
/**
* 要处理的图片目录
*/
File dir = new File("d:/pictrue/src");
/**
* 列出目录中的图片,得到数组
*/
File[] files = dir.listFiles();
/**
* 遍历数组
*/
for(int l=0;l<files.length;l++){
/**
* 定义一个RGB的数组,因为图片的RGB模式是由三个 0-255来表示的 比如白色就是(255,255,255)
*/
int[] rgb = new int[3];
/**
* 用来处理图片的缓冲流
*/
BufferedImage bimage = null;
try {
/**
* 用ImageIO将图片读入到缓冲中
*/
bimage = ImageIO.read(files[l]);
} catch (Exception e) {
e.printStackTrace();
}
/**
* 得到图片的长宽
*/
int width = bimage.getWidth();
int height = bimage.getHeight();
int minx = bimage.getMinX();
int miny = bimage.getMinY();
System.out.println("正在处理:"+files[l].getName());
/**
* 这里是遍历图片的像素,因为要处理图片的背色,所以要把指定像素上的颜色换成目标颜色
* 这里 是一个二层循环,遍历长和宽上的每个像素
*/
for (int i = minx; i < width; i++) {
for (int j = miny; j < height; j++) {
// System.out.print(bi.getRGB(jw, ih));
/**
* 得到指定像素(i,j)上的RGB值,
*/
int pixel = bi.getRGB(i, j);
/**
* 分别进行位操作得到 r g b上的值
*/
rgb[0] = (pixel & 0xff0000) >> 16;
rgb[1] = (pixel & 0xff00) >> 8;
rgb[2] = (pixel & 0xff);
/**
* 进行换色操作,我这里是要把蓝底换成白底,那么就判断图片中rgb值是否在蓝色范围的像素
*/
// if(rgb[0]<140&&rgb[0]>100 && rgb[1]<80&&rgb[1]>50 && rgb[2]<170&&rgb[2]>150 ){
if(rgb[0]<256&&rgb[0]>230 && rgb[1]<256&&rgb[1]>230 && rgb[2]<256&&rgb[2]>230 ){
/**
* 这里是判断通过,则把该像素换成白色
*/
bimage.setRGB(i, j, 0x000000);
}
if(rgb[0]<140&&rgb[0]>100 && rgb[1]<80&&rgb[1]>50 && rgb[2]<170&&rgb[2]>150 ){
/**
* 这里是判断通过,则把该像素换成白色
*/
bimage.setRGB(i, j, 0xffffff);
}
}
}
System.out.println("******完成:"+files[l].getName());
System.out.println();
/**
* 将缓冲对象保存到新文件中
*/
FileOutputStream fos = new FileOutputStream(new File("d:/picture/des/"+files[l].getName()+".png"));
ImageIO.write(bimage,"png", fos);
fos.flush();
fos.close();
}
}
}
二、图像去雾资源:
https://support.huaweicloud.com/sdkreference-image/zh-cn_topic_0250471704.html
三、图像缩放处理(转载)
package com.cy.thumb;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class Thumb {
public static void main(String[] args) throws IOException {
//把图片image.png 长宽等比缩小5倍。
reduceImage("E:/image.png", "E:/image1.png", 5);
//把图片image.png 长宽各设置为100
reduceImage("E:/image.png", "E:/image2.png", 100, 100);
}
/**
* 对图片进行剪裁 返回字节数组
* @param is 图片输入流
* @param width 裁剪图片的宽
* @param height 裁剪图片的高
* @param imageFormat 输出图片的格式 "jpeg jpg等"
* @return
*/
public static byte[] clipImage(InputStream is,int width, int height, String imageFormat){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
// 构造Image对象
BufferedImage src = javax.imageio.ImageIO.read(is);
// 缩小边长
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 绘制 缩小 后的图片
tag.getGraphics().drawImage(src, 0, 0, width, height, null);
ImageIO.write(tag, imageFormat, bos);
} catch (IOException e) {
e.printStackTrace();
}
return bos.toByteArray();
}
/**
* 重置图片大小
* @param srcImagePath 读取图片路径
* @param toImagePath 写入图片路径
* @param width 重新设置图片的宽
* @param height 重新设置图片的高
* @throws IOException
*/
public static void reduceImage(String srcImagePath,String toImagePath,int width, int height) throws IOException{
FileOutputStream out = null;
try{
//读入文件
File file = new File(srcImagePath);
// 构造Image对象
BufferedImage src = javax.imageio.ImageIO.read(file);
// 缩小边长
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 绘制 缩小 后的图片
tag.getGraphics().drawImage(src, 0, 0, width, height, null);
out = new FileOutputStream(toImagePath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
}catch(Exception e){
e.printStackTrace();
}finally{
if(out != null){
out.close();
}
}
}
/**
* 按倍率缩小图片
* @param srcImagePath 读取图片路径
* @param toImagePath 写入图片路径
* @param ratio 缩小比率 宽、高一起等比率缩小
* @throws IOException
*/
public static void reduceImage(String srcImagePath,String toImagePath,int ratio) throws IOException{
FileOutputStream out = null;
try{
//读入文件
File file = new File(srcImagePath);
// 构造Image对象
BufferedImage src = javax.imageio.ImageIO.read(file);
int width = src.getWidth();
int height = src.getHeight();
// 缩小边长
BufferedImage tag = new BufferedImage(width / ratio, height / ratio, BufferedImage.TYPE_INT_RGB);
// 绘制 缩小 后的图片
tag.getGraphics().drawImage(src, 0, 0, width / ratio, height / ratio, null);
out = new FileOutputStream(toImagePath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
}catch(Exception e){
e.printStackTrace();
}finally{
if(out != null){
out.close();
}
}
}
/**
* 对图片裁剪,并把裁剪新图片保存
* @param srcPath 读取源图片路径
* @param toPath 写入图片路径
* @param x 剪切起始点x坐标
* @param y 剪切起始点y坐标
* @param width 剪切宽度
* @param height 剪切高度
* @param readImageFormat 读取图片格式
* @param writeImageFormat 写入图片格式
*/
public static void cropImage(String srcPath, String toPath, int x,int y,int width,int height, String readImageFormat,String writeImageFormat){
FileInputStream fis = null ;
ImageInputStream iis =null ;
try{
//读取图片文件
fis = new FileInputStream(srcPath);
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(readImageFormat);
ImageReader reader = readers.next();
//获取图片流
iis = ImageIO.createImageInputStream(fis);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
//定义一个矩形
Rectangle rect = new Rectangle(x, y, width, height);
//提供一个 BufferedImage,将其用作解码像素数据的目标。
param.setSourceRegion(rect);
BufferedImage bi = reader.read(0, param);
//保存新图片
ImageIO.write(bi, writeImageFormat, new File(toPath));
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(fis!=null){
fis.close();
}
if(iis!=null){
iis.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
四、实现图片上传并添加水印(转载)
/**
* 图片上传,添加水印
* @param request
* @param params
* @param values
* @return
* @throws Exception
* @author LLJ
* @date 2016/12/16
*/
public static List<Map<String, Object>> newUpload(HttpServletRequest request,
String[] params, Map<String, Object[]> values) throws Exception {
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = mRequest.getFileMap();
String relativePath = FileOperateUtil.UPLOADDIR + DateUtils.dateStr7(new Date()) + "/";
logger.info("图片relativePath:"+relativePath);
String uploadDir = request.getSession().getServletContext().getRealPath("/") + "/" + relativePath;
logger.info("图片uploadDir:"+uploadDir);
File file = new File(uploadDir);
if (!file.exists()) {
file.mkdirs();
}
String fileName = null;
int i = 0;
for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext(); i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("success", true);
Map.Entry<String, MultipartFile> entry = it.next();
MultipartFile mFile = entry.getValue();
//判断文件格式 和 文件大小
if(mFile.getSize()/1024D>NEW_LIMIT_SIZE){
map.put("success", false);
map.put("msg", "图片仅支持小于3M的jpg、 png.格式");
result.add(map);
continue;
}
//获取文件名
fileName = mFile.getOriginalFilename();
if(fileName.lastIndexOf(".")<0 || fileName.lastIndexOf(".")==fileName.length()-1){
map.put("success", false);
map.put("msg", "图片仅支持小于3M的jpg、 png.格式");
result.add(map);
continue;
}
if(!Pattern.matches("^"+NEW_LIMIT_TYPE+"$", fileName.substring(fileName.lastIndexOf(".")+1))){
map.put("success", false);
map.put("msg", "文件上传格式不对,只支持jpg、 png格式");
result.add(map);
continue;
}
String storeName = rename(fileName);
String noZipName = uploadDir + storeName;
String zipName = zipName(noZipName);
logger.info("图片zipName:"+zipName);
File uploadFile = new File(uploadDir + storeName);
FileCopyUtils.copy(mFile.getBytes(), uploadFile);
// 固定参数值对
map.put(FileOperateUtil.REALNAME, fileName);
map.put(FileOperateUtil.STORENAME, storeName);
map.put(FileOperateUtil.SIZE, new File(zipName).length());
map.put(FileOperateUtil.SUFFIX, "zip");
map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream");
map.put(FileOperateUtil.CREATETIME, new Date());
map.put("url", relativePath + storeName);
logger.info("图片url:"+relativePath + storeName);
fileName = map.get(FileOperateUtil.STORENAME) + "";
/**开始:加水印**/
FileInputStream in=new FileInputStream(uploadDir + "/" + fileName);
Image src=ImageIO.read(in);
int w=src.getWidth(null);
int h=src.getHeight(null);
float alpha = 0.3f; // 透明度
BufferedImage img=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);//构建画板
Graphics2D g=img.createGraphics();//得到画笔
g.drawImage(src,0,0,w,h,null);//把源图片写入画板
Font fsib30 = new Font("微软雅黑", Font.BOLD + Font.ITALIC, img.getWidth()/16);
g.setFont(fsib30);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha));
g.setColor(Color.black);
g.setBackground(Color.white);
g.rotate(Math.toRadians(-15),
(double) img.getWidth() / 2, (double) img
.getHeight() / 2);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
String pressText = "仅供XXX认证使用";
g.drawString(pressText, (w - (getLength(pressText) * img.getWidth()/16))
/ 2 + 10, (h - img.getWidth()/16) / 2 + 10);
g.dispose();//生成图片
OutputStream out = new FileOutputStream(uploadDir + "/" + fileName);
JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(out);
en.encode(img);
/**结束:加水印**/
// 自定义参数值对
for (String param : params) {
map.put(param, values.get(param)[i]);
}
result.add(map);
}
return result;
}
/**
* 获取字符长度,一个汉字作为 1 个字符, 一个英文字母作为 0.5 个字符
* @param text
* @return 字符长度,如:text="中国",返回 2;text="test",返回 2;text="中国ABC",返回 4.
*/
public static int getLength(String text) {
int textLength = text.length();
int length = textLength;
for (int i = 0; i < textLength; i++) {
if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
length++;
}
}
return (length % 2 == 0) ? length / 2 : length / 2 + 1;
}