本文主要实现以下几个功能:
1、先通过IM4java的功能将本地的一张图片剪切出来形成新的图片
2、通过上传功能,将裁剪的图片上传到mongodb数据库中储存
3、再从mongodb数据库中取出刚才上传的图片
1、首先是对本地图片的裁剪,
首先安装参考:https://www.cnblogs.com/wbxk/p/9794094.html
然后在本地存放一张图片
存放一张link-light-1.jpg的图片,然后编写测试的工具类,
导入本次需要的jar包
<!-- 添加mongoDB -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.2.0</version>
</dependency>
<!-- 添加imageMagick -->
<dependency>
<groupId>org.im4java</groupId>
<artifactId>im4java</artifactId>
<version>1.4.0</version>
</dependency>
主要是用于运行程序的
代码如下:
import org.springframework.beans.factory.annotation.Value;
import cn.xtkj.common.utils.Im4JavaUtils;
public class Im4Test {
//源图片目录
@Value(value = "upload.path")
//private static String oldimageurl;
public static final String SRC_IMAGE_PATH = "C:\\xxxx\\upload\\";
public static final String NEW_IMAGE_PATH = "C:\\xxxx\\upload\\new\\";
public static void main(String[] args) {
String str = "1418-193-1487-289";//要裁剪取区域
String[] newarry = str.split("-");
int startX = 0;
int startY = 0;
int endX = 0;
int endY = 0;
startX = Integer.parseInt(newarry[0]);
startY = Integer.parseInt(newarry[1]);
endX = Integer.parseInt(newarry[2]);
endY = Integer.parseInt(newarry[3]);
int width = endX - startX;
int hight = endY - startY;
Im4JavaUtils.cutImage(SRC_IMAGE_PATH +"/"+ "link-light-1.jpg", NEW_IMAGE_PATH + "2.jpg", width, hight, startX, startY);
}
}
图片裁剪之后将其命名为2.jpg,并放到里面的new的文件夹中,其中工具类Im4JavaUtils代码如下:
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import org.im4java.core.CompositeCmd;
import org.im4java.core.ConvertCmd;
import org.im4java.core.IMOperation;
import org.im4java.core.IdentifyCmd;
import org.im4java.core.ImageCommand;
import org.im4java.process.ArrayListOutputConsumer;
public class Im4JavaUtils {
private static final String IMAGE_MAGICK_PATH = "C:\\Program Files\\ImageMagick-7.0.8-Q16";
enum CommandType {
convert("转换处理"), composite("图片合成"), identify("图片信息"),;
private String name;
CommandType(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* 处理图片
* @param command
* @return
*/
private static ImageCommand getImageCommand(CommandType command) {
ImageCommand cmd = null;
switch (command) {
case convert:
cmd = new ConvertCmd();
break;
case composite:
cmd = new CompositeCmd();
break;
case identify:
cmd = new IdentifyCmd();
break;
}
if (cmd != null) {
cmd.setSearchPath(IMAGE_MAGICK_PATH);
}
return cmd;
}
/**
* 旋转图片
*
* @param srcImagePath 原图片地址
* @param newImagePath 新图片地址
* @param degree 旋转角度
* @return
*/
public static boolean roateImage(String srcImagePath, String newImagePath, Double degree) {
try {
IMOperation op = new IMOperation();
op.addImage(srcImagePath);
op.rotate(degree);
op.addImage(newImagePath);
ImageCommand convert = getImageCommand(CommandType.convert);
convert.run(op);
System.out.println("旋转图片成功");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 裁剪图片
*
* @param srcImagePath 原图片地址
* @param newImagePath 新图片地址
* @param width 裁剪后的宽度
* @param height 裁剪后的高度
* @param x 起始横坐标
* @param y 起始纵坐标
* @return
*/
public static boolean cutImage(String srcImagePath, String newImagePath, Integer width, Integer height, Integer x,
Integer y) {
try {
IMOperation op = new IMOperation();
op.addImage(srcImagePath);
op.crop(width, height, x, y);
op.addImage(newImagePath);
ImageCommand convert = getImageCommand(CommandType.convert);
convert.run(op);
System.out.println("裁剪图片成功");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 缩放图片
*
* @param srcImagePath 原图片地址
* @param newImagePath 新图片地址
* @param width 缩放后的宽度
* @param height 缩放后的高度 高度和宽度需符合图片比例,不符合的情况下,以其中最小值为准。
* @return
*/
public static boolean zoomImage(String srcImagePath, String newImagePath, Integer width, Integer height) {
try {
IMOperation op = new IMOperation();
op.addImage(srcImagePath);
op.resize(width, height);
op.addImage(newImagePath);
ImageCommand convert = getImageCommand(CommandType.convert);
convert.run(op);
System.out.println("缩放图片成功");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 压缩图片
*
* @param srcImagePath 原图片地址
* @param newImagePath 新图片地址
* @param quality 压缩比例 图片压缩比,有效值范围是0.0-100.0,数值越大,缩略图越清晰。
* @return
*/
public static boolean compressImage(String srcImagePath, String newImagePath, Double quality) {
try {
IMOperation op = new IMOperation();
op.addImage(srcImagePath);
op.quality(quality);
op.addImage(newImagePath);
ImageCommand convert = getImageCommand(CommandType.convert);
convert.run(op);
System.out.println("压缩图片成功");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 文字水印
*
* @param srcImagePath 原图片地址
* @param newImagePath 新图片地址
* @param content 水印文字,不支持汉字
* @return
*/
public static boolean textImage(String srcImagePath, String newImagePath, String content) {
try {
IMOperation op = new IMOperation();
op.addImage(srcImagePath);
// 右下角
op.font("ArialBold").gravity("southeast").pointsize(60).fill("#F2F2F2").draw("text 10,10 " + content);
op.addImage(newImagePath);
ImageCommand convert = getImageCommand(CommandType.convert);
convert.run(op);
System.out.println("添加文字水印成功");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 图片水印
*
* @param srcImagePath 原图片地址
* @param newImagePath 新图片地址
* @param appendImagePath 水印图片地址
* @param dissolve 水印透明度,0-100
* @return
*/
public static boolean compositeImage(String srcImagePath, String newImagePath, String appendImagePath,
Integer dissolve) {
try {
// 原图片信息
BufferedImage bufferedImage = ImageIO.read(new File(srcImagePath));
int w = bufferedImage.getWidth();
int h = bufferedImage.getHeight();
// 水印图片信息
Image image = ImageIO.read(new File(appendImagePath));
int w1 = image.getWidth(null);
int h1 = image.getHeight(null);
IMOperation op = new IMOperation();
op.geometry(w1, h1, w - w1 - 10, h - h1 - 10);
op.dissolve(dissolve);
op.addImage(appendImagePath);
op.addImage(srcImagePath);
op.addImage(newImagePath);
ImageCommand composite = getImageCommand(CommandType.composite);
composite.run(op);
System.out.println("添加图片水印成功");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 219 * 获取图片信息 220
* @param imagePath 图片地址 221
* @return 222
*/
public static Map<String, String> getImageInfo(String imagePath) {
Map<String, String> imageInfo = new HashMap<>();
try {
IMOperation op = new IMOperation();
op.format("%w,%h,%d/%f,%Q,%b,%e");
op.addImage();
ImageCommand identifyCmd = getImageCommand(CommandType.identify);// 注意这里,用的是identify
ArrayListOutputConsumer output = new ArrayListOutputConsumer();
identifyCmd.setOutputConsumer(output);
identifyCmd.run(op, imagePath);
ArrayList<String> cmdOutput = output.getOutput();
String[] result = cmdOutput.get(0).split(",");
if (result.length == 6) {
imageInfo.put("宽度", result[0]);
imageInfo.put("高度", result[1]);
imageInfo.put("路径", result[2]);
imageInfo.put("质量", result[3]);
imageInfo.put("大小", result[4]);
imageInfo.put("格式", result[5]);
}
} catch (Exception e) {
e.printStackTrace();
}
return imageInfo;
}
public static void dealImage(String XYnumlocation,String ImageName,String oldimageurl) {
String[] newarry = XYnumlocation.split("-");
int startX = 0;
int startY = 0;
int endX = 0;
int endY = 0;
startX = Integer.parseInt(newarry[0]);
startY = Integer.parseInt(newarry[1]);
endX = Integer.parseInt(newarry[2]);
endY = Integer.parseInt(newarry[3]);
int width = endX - startX;
int hight = endY - startY;
String newimgeurl = oldimageurl+"/"+"new/"+ ImageName;
Im4JavaUtils.cutImage(oldimageurl +"/"+ ImageName,newimgeurl, width, hight, startX, startY);
}
}
运行程序后得到裁剪的图片,
2、开始使用mongodb数据库下载地址我已经上传了,下载地址:
https://download.csdn.net/download/qq_34178998/10931742
安装过后启动服务:,
配置环境变量
同时在安装目录下
data文件夹中新建一个db的新的文件夹,并且在bin的文件夹中新建一个配置文件:
配置文件内容为;
最后进入dos界面,输入mongo
说明成功,输入cls清空一下,然后依次进入数据库,表
查询该表中的数据
编写图片上传的demo
代码如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.util.LinkedHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import com.mongodb.gridfs.GridFSInputFile;
public class GridFSDemo {
public static void main(String[] args) throws FileNotFoundException
{
/*
* 1、创建数据库连接
*/
Mongo client= new Mongo("localhost",27017);
//取得数据库对象
DB db=client.getDB("mongoTest");
String collectionName="mongoCollectionTest";
//创建数据库对象中GridFS集合
GridFS gridFS= new GridFS(db,collectionName);
/*
* 2、上传文件
*/
//创建测试文件,mongo 默认存在该文件
File file=new File("C:/xxxx/upload/new/2.jpg");
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
map.put("filename",file.getName());//可以给文件重新命名
map.put("contentType", "application/jpg");
//GridFSFile returnmsg = useMongodb.uploadFile(file, null, "mongoTest", collectionName, map);
FileInputStream fileInputStream=new FileInputStream(file);
//创建gridFS文件数据流
GridFSInputFile createFile=gridFS.createFile(fileInputStream);
//设置文件属性
createFile.put("filename", "小小.jpg");
createFile.put("contentType", "application/jpg");
createFile.save();
/*
* 3、根据id查询上传文件
*/
GridFSDBFile findOne= gridFS.findOne(new BasicDBObject("id",createFile.getId()));
System.out.print("---------"+findOne);
/*
* 4、查询所有文件列表
* DBCursor 数据库游标
*/
// DBCursor fileList=gridFS.getFileList();
// while(fileList.hasNext())
// {
// System.out.print(fileList.next());
// }
/*
*5、 删除文件
*/
// gridFS.remove(new BasicDBObject("filename","大大.jpg"));
// client.close();
}
}
上传完成之后,再次进入dos查询一下
刚才的图片已经上传上去,接下来就是下载下来
3、下载图片本人是利用已有的项目的一个接口测试的
代码如下:
/**
* 测试取出图片
* @throws IOException
*/
@GetMapping(value = "/show")
@ApiOperation(value = "展示图片")
public void show(HttpServletRequest request, HttpServletResponse response,String picnewName) throws IOException{
Mongo client= new Mongo("localhost",27017);
//取得数据库对象
DB db=client.getDB("mongoTest");
String collectionName="mongoCollectionTest";
String filename=request.getParameter("fileId");
// 获取fs的根节点
GridFS gridFS = new GridFS(db, collectionName);
//GridFSDBFile file = fileService.retrieveFileOne("fs", filename);
GridFSDBFile file = gridFS.findOne(picnewName);
InputStream in = file.getInputStream();
filename=(String) file.get("filename");
filename=filename.replace(" ", "");
String fileName = new String(filename.getBytes("GB2312"), "ISO_8859_1");
filename = fileName;
//response.setCharacterEncoding("UTF-8");
response.setContentType(file.getContentType());
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[2048];
int i = -1;
while ((i = in.read(buffer)) != -1) {
out.write(buffer, 0, i);
}
in.close();
out.flush();
out.close();
}
最后跑起项目看看能不能下载刚才上传的图片
接口测试
得到结果
完成