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 ...
随机推荐
- TortoiseSVN使用svn+ssh协议连接服务器时重复提示输入密码
当使用svn+ssh协议连接svn服务器时,ssh会提示请求认证,由于不是svn客户端程序来完成ssh的认证,所以不会缓存密码. 而svn客户端通常会建立多个版本库的连接,当密码没有缓存的时候,就会重 ...
- DAY3-Flask项目
1.jsonify: 得到了从API获得的数据并返回,API返回的json数据被转化成dict,我们还需要把dict序列化: return json.dump(result), 200, {'cont ...
- P2144 [FJOI2007]轮状病毒
题目描述 轮状病毒有很多变种.许多轮状病毒都是由一个轮状基产生.一个n轮状基由圆环上n个不同的基原子和圆心的一个核原子构成.2个原子之间的边表示这2个原子之间的信息通道,如图1. n轮状病毒的产生规律 ...
- mysql事务隔离级别设置
设置innodb的事务级别方法是:set 作用域 transaction isolation level 事务隔离级别: 若没有输入作用域直接修改transaction isolation,显示修改成 ...
- CF1009F Dominant Indices 解题报告
CF1009F Dominant Indices 题意简述 给出一颗以\(1\)为跟的有根树,定义\(d_{i,j}\)为以\(i\)为根节点的子树中到\(i\)的距离恰好为\(j\)的点的个数,对每 ...
- 使用IPMI控制/监控Linux服务器
1 IPMI简述 IPMI提供了很多丰富功能,我使用的功能,说得大白话一点,就是: 1.获取本设备的硬件信息:包括CPU和主板的温度.电压.风扇转速. 2.在设备A上,通过命令,控制远程设 ...
- php 百家姓
private $surname = array('赵','钱','孙','李','周','吴','郑','王','冯','陈','褚','卫','蒋','沈','韩','杨','朱','秦','尤' ...
- js 读写 cookie 简单实现
const getItem = key => { let ca = document.cookie.split('; '); for (let i = 0; i < ca.length; ...
- springcloud之Hystrix
1.Hystrix出现的背景 从上面看来,Hystrix避免了雪崩效益,对于失败的服务可以快速失败. 2.为了解决雪崩效应的解决方案: (1)超时机制 (2)断路器模式Hystrix 3.Hystri ...
- ubuntu thrift
1.下载 http://www.apache.org/dyn/closer.cgi?path=/thrift/0.9.2/thrift-0.9.2.tar.gz 2.解压 tar -xvf thrif ...