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;
}
java后台中处理图片辅助类汇总(上传图片到服务器,从服务器下载图片保存到本地,缩放图片,copy图片,往图片添加水印图片或者文字,生成二维码,删除图片等)的更多相关文章
- java 通过Qrcode生成二维码添加图片logo和文字描述
/** * 二维码创建 * @author yhzm * */ public class printServiceImpl extends BaseService { public void barC ...
- java生成二维码扫码网页自动登录功能
找了很多资料,七七八八都试了一遍,最终写出来了这个功能. 菜鸟一枚,此文只为做笔记. 简单的一个生成二维码,通过网页确认登录,实现二维码页面跳转到主页面. 有三个servlet: CodeServle ...
- 在java中生成二维码,并直接输出到jsp页面
在java中生成的二维码不存到磁盘里要直接输出到页面上,这就需要把生成的二维码直接以流的形式输出到页面上,我用的是myeclipse 和 tomcat 它的原理是:在加载页面时,根据img的src(c ...
- Java后台直接生成二维码介绍
Java后台直接生成二维码 1.其实jquery也可以直接生成二维码的,但我测试的时候,二维码生成后太模糊,难以识别.所以在这里介绍在后来生成二维码的方式. 2.不善于文字描述,直接上代码了. imp ...
- Java与JS生成二维码
1.二维码概念 二维码/二维条码是用某种特定的集合图形按一定规律在平面上(二维方向上)分布的黑白相间的图形记录数据符号信息的图片. 黑线是二进制的1,空白的地方是二进制的0,通过1.0这种数据组合用于 ...
- JAVA生成二维码图片代码
首先需要导入 QRCode.jar 包 下载地址看这里 http://pan.baidu.com/s/1o6qRFqM import java.awt.Color;import java.awt. ...
- java生成二维码(带logo)
之前写过一篇不带logo的二维码实现方式,採用QRCode和ZXing两种方式 http://blog.csdn.net/xiaokui_wingfly/article/details/3947618 ...
- 【Java 二维码】生成二维码
ZXingCodeEncodeUtils 生成及解析二维码项目 package utils; import java.awt.BasicStroke; import java.awt.Color; i ...
- java生成二维码
具体代码如下,作为一个新手,期待与你一起交流: import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.Buf ...
随机推荐
- IE 低版本 透明度
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- struts 跳转的四种常用类型
1 dispatcher 默认的跳转类型 地址栏不变 2.redirect 跳转后地址会变化 3 chain 跳转到一个动作类 地址栏不会变 4 redirectAction 跳转到一个动作类 地址栏 ...
- STL 容器的概念
STL 容器的概念 在实际的开发过程中,数据结构本身的重要性不会逊于操作于数据结构的算法的重要性,当程序中存在着对时间要求很高的部分时,数据结构的选择就显得更加重要. 经典的数据结构数量有限,但是我们 ...
- 【刷题】BZOJ 2588 Spoj 10628. Count on a tree
Description 给定一棵N个节点的树,每个点有一个权值,对于M个询问(u,v,k),你需要回答u xor lastans和v这两个节点间第K小的点权.其中lastans是上一个询问的答案,初始 ...
- 内容显示在HTML页面底端的一些处理方式
1.概要: 手机页面底端有时候需要显示版权信息,诸如一行文字或者一个背景图片,但是页面的滚动长度未知,需要考虑两个问题 当页面高度小于屏幕高度时候: 希望最后一行信息显示在屏幕底端,同时也就是页面底端 ...
- BZOJ2436 [Noi2011]Noi嘉年华 【dp】
题目链接 BZOJ2436 题解 看这\(O(n^3)\)的数据范围,可以想到区间\(dp\) 发现同一个会场的活动可以重叠,所以暴力求出\(num[l][r]\)表示离散化后\([l,r]\)的完整 ...
- 【hdu4285】 circuits
http://acm.hdu.edu.cn/showproblem.php?pid=4285 (题目链接) 题意 求不不能嵌套的回路个数为K的路径方案数. Solution 插头dp,时限卡得太紧了, ...
- 针对Weblogic测试的一些小总结(转)
1. 管理员登录页面弱密码 Weblogic的端口一般为7001,弱密码一般为weblogic/Oracle@123 or weblogic,或者根据具体情况进行猜测,公司名,人名等等,再有就可以用b ...
- Redis事务介绍
概述 相信学过Mysql等其他数据库的同学对事务这个词都不陌生,事务表示的是一组动作,这组动作要么全部执行,要么全部不执行.为什么会有这样的需求呢?看看下面的场景: 微博是一个弱关系型社交网络,用户之 ...
- Webpack + React 开发 01 HelloWorld
1.项目依赖 安装所需要依赖的其它第三方开源库,项目依赖如下: "dependencies": { "babel-core": "^6.21.0&qu ...