java后台中处理图片辅助类汇总(上传图片到服务器,从服务器下载图片保存到本地,缩放图片,copy图片,往图片添加水印图片或者文字,生成二维码,删除图片等)

最近工作中处理小程序宝箱活动,需要java画海报,所以把这块都快百度遍了,记录一下处理的方法,百度博客上面也有不少坑!

获取本地图片路径:

String bgPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath().replaceAll("WEB-INF/classes/","")+"assets/img/01.jpg";
这里主要是java里面获取资源路径,需要其他的可以百度就好

上传图片到服务器

/**
* 上传图片,返回图片地址
* @param file 上传的文件
* @param wxcid 参数
* @return
*/
public static String decaptcha(File file,String wxcid) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://"+wxcid); //请求接口,接口接受参数是MultipartFile就可以用这个
RequestConfig config = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(20000).build();
post.setConfig(config);
     //这里除了httpclient之外还需要一个依赖httpmime,我用的4.5.2没问题,版本坑也很多,注意选择
FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("uploadfile", fileBody);
// 相当于 <input type="file" class="file" name="file">,匹配@RequestParam("file")
// .addPart()可以设置模拟浏览器<input/>的表单提交
HttpEntity entity = builder.build();
post.setEntity(entity);
String result = "";
try {
CloseableHttpResponse e = client.execute(post);
HttpEntity resEntity = e.getEntity();
if(entity != null) {
result = EntityUtils.toString(resEntity);
System.out.println("response content:" + result);
}
} catch (IOException var10) {
log.error("请求解析验证码io异常",var10);
var10.printStackTrace();
}
return result;
}

  

缩放图片

  //缩放图片: 目标文件路径,缩放后保存的路径,缩放的宽高,这里都是根据本地路径来的,可以根据需求适当自己修改
public static void reduceImg(String imgsrc, String imgdist, int widthdist,
int heightdist,boolean isCir) {//是否设置成圆形
try {
File srcfile = new File(imgsrc);
if (!srcfile.exists()) {
return;
}
Image src = javax.imageio.ImageIO.read(srcfile);
BufferedImage tag= new BufferedImage((int) widthdist, (int) heightdist,
BufferedImage.TYPE_4BYTE_ABGR);
//Graphics graphics = tag.getGraphics();
Graphics2D graphics = tag.createGraphics();
// 设置“抗锯齿”的属性(这里好像不管用,很蛋疼)
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//设置成圆形
if(isCir){
Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, 50, 50);
graphics.setClip(shape);
}
graphics.drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
graphics.dispose();
FileOutputStream out = new FileOutputStream(imgdist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

  

copy图片

  // 拷贝图片
public static void copyFile(String srcPath, String destPath) throws IOException {
// 打开输入流
FileInputStream fis = new FileInputStream(srcPath);
// 打开输出流
FileOutputStream fos = new FileOutputStream(destPath); // 读取和写入信息
int len = 0;
while ((len = fis.read()) != -1) {
fos.write(len);
}
// 关闭流 先开后关 后开先关
fos.close(); // 后开先关
fis.close(); // 先开后关
}

  

往图片上添加水印

添加文字:

/**
* 打印文字水印图片
*
* @param pressText
* --文字
* @param targetImg --
* 目标图片
* @param fontName --
* 字体名
* @param fontStyle --
* 字体样式
* @param color --
* 字体颜色
* @param fontSize --
* 字体大小
* @param x --
* 偏移量
* @param y
*/ public static void pressText(String pressText, String targetImg,
String fontName, int fontStyle, Color color, int fontSize, int x,
int y) {
try {
File _file = new File(targetImg);
Image src = ImageIO.read(_file);
int wideth = src.getWidth(null);
int height = src.getHeight(null);
BufferedImage image = new BufferedImage(wideth, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
// 设置“抗锯齿”的属性
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.drawImage(src, 0, 0, wideth, height, null);
g.setColor(color);
AttributedString ats = new AttributedString(pressText);
Font font = new Font(fontName, fontStyle, fontSize);
g.setFont(font);
ats.addAttribute(TextAttribute.FONT, font, 0, pressText.length());
AttributedCharacterIterator iter = ats.getIterator();
/* 添加水印的文字和设置水印文字出现的内容 ----位置 */
g.drawString(iter, x, y);
g.dispose();
FileOutputStream out = new FileOutputStream(targetImg);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}

  

添加图片:

/**
* 把图片印刷到图片上
*
* @param pressImg --
* 水印文件
* @param targetImg --
* 目标文件
* @param x
* --x坐标
* @param y
* --y坐标
*/
public final static void pressImage(String pressImg, String targetImg,
int x, int y) {
try {
//目标文件
File _file = new File(targetImg);
Image src = ImageIO.read(_file);
int wideth = src.getWidth(null);
int height = src.getHeight(null);
BufferedImage image = new BufferedImage(wideth, height,
BufferedImage.TYPE_INT_RGB);
//Graphics g = image.createGraphics();
Graphics2D g = image.createGraphics();
// 设置“抗锯齿”的属性
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.drawImage(src, 0, 0, wideth, height, null);
//水印文件
File _filebiao = new File(pressImg);
Image src_biao = ImageIO.read(_filebiao);
g.drawImage(src_biao, x, y, null);
//水印文件结束
g.dispose();
FileOutputStream out = new FileOutputStream(targetImg);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

  注意的是,这里得抗锯齿好像都不管用

删除图片

/**
* 根据路径删除图片
* @param path
*/
public static void deleteFile(String path){
File file= new File(path);
if(file.exists()){
log.debug("del:"+file.delete());
}
}

  

从服务器下载图片到本地

    /*
* 根据;;链接下载图片到本地,链接(http://.....)
*/
public static String downloadByPath(String urlpath,String filename){
InputStream mainis = null;
String logoPath="";
try {
URL url = new URL(urlpath);
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5*1000);
// 输入流
mainis = con.getInputStream();
//通过JPEG图象流创建JPEG数据流解码器
JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(mainis);
//解码当前JPEG数据流,返回BufferedImage对象
BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage();
       // 保存到本地的地址
logoPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath() + "/" + new String(new Date().getTime() + filename+".jpg");
OutputStream os = new FileOutputStream(logoPath);
//创键编码器,用于编码内存中的图象数据。
JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
en.encode(buffImg);
mainis.close();
os.close();
return logoPath;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

  这里有个坑,如果服务器上图片是png或者其他格式,就会报异常 Not a JPEG格式文件,所以一般用下面这种就好:

public static String downloadByPath(String urlpath,String filename) {
String logoPath ="";
try {
URL url = new URL(urlpath);
URLConnection conn = null;
conn =url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] getData = readInputStream(inputStream);
logoPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath() + "/" + new String(new Date().getTime()+urlpath.substring(urlpath.length()-4));
//文件保存位置
File file = new File(logoPath);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if(fos!=null){
fos.close();
}
if(inputStream!=null){
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return logoPath;
}

  这种可以适应所有的格式!

生成一般二维码

/**
* 生成二维码
* @param createPath 生成二维码路径
* @param exurl 扫码跳转url(包含参数等信息)
*/
public static void createQrcodePicByPath(String createPath, String exurl){
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix;
try {
//这里指定大小
bitMatrix = multiFormatWriter.encode(exurl, BarcodeFormat.QR_CODE, 220, 220, hints);
/*bitMatrix = deleteWhite(bitMatrix);*/
BufferedImage bimage = toBufferedImage(bitMatrix);
OutputStream os = new FileOutputStream(createPath);
//创键编码器,用于编码内存中的图象数据。
JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
en.encode(bimage);
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

  

httpclent请求地址生成特殊二维码(小程序):

  // 获取小程序二维码,需要的参数,这里主要是httpclient发送get请求,解析返回结果(图片地址)
public static String createQrcodePicByMiniProgramma(String wxcid, String token,String path){
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
URIBuilder builder = new URIBuilder("http://......");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cid",wxcid));
params.add(new BasicNameValuePair("token",token));
params.add(new BasicNameValuePair("path",path));
builder.setParameters(params);
HttpGet get = new HttpGet(builder.build());
response = httpClient.execute(get);
if(response != null && response.getStatusLine().getStatusCode() == 200){
HttpEntity entity = response.getEntity();
String string = entityToString(entity);
log.info("pms消息转发成功,返回结果"+string);
return string;
}
} catch (Exception e) {
e.printStackTrace();log.error("pms消息转发失败"+response.getEntity());
} finally {
try {
httpClient.close();if(response != null)response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

  

//解析httpclient返回结果,转换成String
private static String entityToString(HttpEntity entity) throws IOException {
String result = null;
if(entity != null)
{
long lenth = entity.getContentLength();
if(lenth != -1 && lenth < 2048){
result = EntityUtils.toString(entity,"UTF-8");
}else {
InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
CharArrayBuffer buffer = new CharArrayBuffer(2048);
char[] tmp = new char[1024];
int l;
while((l = reader1.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
result = buffer.toString();
}
}
return result;
}

 

上一篇:Python3多线程之间的执行顺序问题


下一篇:实时输出topk最频繁变动的股价