圖片上傳 mongo + get請求帶 token 預覽 圖片 生成gif動圖
阿新 • • 發佈:2020-08-19
<!-- 圖片轉gif動圖 --> <dependency> <groupId>com.madgag</groupId> <artifactId>animated-gif-lib</artifactId> <version>1.4</version> </dependency>
<!-- mogodb 的支援--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>2.2.2.RELEASE</version> </dependency>
controller層
import cn.hutool.core.convert.Convert; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import springfox.documentation.annotations.ApiIgnore; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * <p> * 圖片上傳和預覽控制器 * </p> * */ @RestController @RequestMapping("/image/upload") @Api(value = "圖片上傳和預覽controller", tags = {"圖片上傳和預覽介面"}) public class ImageUploadController { @Autowired private ImageUploadService imageUploadService; @ApiOperation(value = "圖片上傳", notes = "圖片上傳上傳", httpMethod = "POST") @PostMapping("/image/upload") public String imageUpload(@RequestParam("file") MultipartFile file){ return this.imageUploadService.imageUpload(file); } @ApiOperation(value = "基層資料查詢成果預覽", notes = "基層資料查詢成果預覽", httpMethod = "GET") @ApiImplicitParam(name = "imageid", value = "圖片存mongo中的id", required = true, dataType = "String") @GetMapping("/image/{imageid}/preview.png") public byte[] previewPng(@RequestParam("imageid")String imageid){ return this.imageUploadService.previewPng(imageid); } }
service 層
import com.baomidou.mybatisplus.extension.service.IService; import com.sgis.one.map.micro.analysis.model.entity.TMicroAchievement; import com.sgis.one.map.micro.analysis.model.vo.SelectMicroAchievementVo; import org.springframework.web.multipart.MultipartFile; import java.util.List; /** * <p> * 圖片上傳和預覽服務類 * </p> */ public interface ImageUploadService extends IService<entityTable> { /** * 圖片上傳 * @param file * @return 圖片存入mongo中的ObjectId */ String imageUpload(MultipartFile file); /** * 圖片預覽 * @param imageid 圖片存入mongo中的ObjectId * @return 圖片的二進位制流 */ byte[] previewPng(String imageid); }
Impl層
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.sgis.common.file.util.MongoService; import com.sgis.common.handler.BusinessException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * <p> * 圖片上傳和預覽實現類 * </p> */ @Service public class ImageUploadServiceImpl extends ServiceImpl<entityMapper, entityTable> implements ImageUploadService { @Autowired private MongoService mongoService; /** * 圖片上傳 * @param file * @param userId * @param fsgisOneMapMacroAnalysis * @return */ @Override public String imageUpload(MultipartFile file, Integer userId, String serviceId) { BufferedImage read = null; try { read = ImageIO.read(file.getInputStream()); } catch (IOException e) { e.printStackTrace(); } if (read == null){ throw new BusinessException(500,"圖片格式不正確"); } String fileName = file.getOriginalFilename(); return this.mongoService.uploadFile(file); } /** * 圖片預覽 * @param imageid * @return */ @Override public byte[] previewPng(String imageid) { return this.mongoService.downloadImageByte(imageid, null); } }
mongoService
import cn.hutool.core.util.ObjectUtil; import com.madgag.gif.fmsware.AnimatedGifEncoder; import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSBuckets; import com.mongodb.client.gridfs.GridFSDownloadStream; import com.mongodb.client.gridfs.GridFSFindIterable; import com.mongodb.client.gridfs.model.GridFSFile; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageDecoder; import org.apache.commons.io.IOUtils; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.gridfs.GridFsResource; import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.awt.image.BufferedImage; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; /** /** *@program: *@description: MongoService */ @Service public class MongoService { @Autowired private GridFsTemplate gridFsTemplate; @Autowired private MongoDbFactory mongoDbFactory; /** * 儲存到本地 * @param fileId * @param path * @param fileName * @throws Exception */ public void downloadToLocal(String fileId,String path,String fileName) throws Exception { try { //查詢單個檔案 Query query = Query.query(Criteria.where("_id").is(fileId)); GridFSFile gfsFile = gridFsTemplate.findOne(query); if (gfsFile == null) { return; } GridFSBucket gridFSBucket= GridFSBuckets.create(mongoDbFactory.getDb()); GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gfsFile.getObjectId()); //建立GridFsResource物件,獲取流 GridFsResource gridFsResource = new GridFsResource(gfsFile, gridFSDownloadStream); FileOutputStream downloadFile = new FileOutputStream(path + File.separator + fileName); IOUtils.copy(gridFsResource.getInputStream(),downloadFile); }catch (Exception e) { e.printStackTrace(); } } /** * 檔案上傳到mongo伺服器上 * @param multipartFile 檔案 * @param fileName 存入mongo中的名字 * @return * @throws Exception */ public ApiResult<FileInfo> uploadFile(MultipartFile multipartFile,String fileName) throws Exception{ //檢視mongo中是否已經儲存圖片 Query filename = Query.query(Criteria.where("filename").is(fileName)); GridFSFile one = this.gridFsTemplate.findOne(filename); if (ObjectUtil.isNotNull(one)){ Query deleteQuery = Query.query(Criteria.where("_id").is(one.getId())); this.gridFsTemplate.delete(deleteQuery); } // 獲得檔案輸入流 InputStream fileIn = multipartFile.getInputStream(); // 將檔案儲存到mongodb中,mongodb 將會返回這個檔案的具體資訊 ObjectId objectId = gridFsTemplate.store(fileIn,fileName); return objectId.toString(); } /** * GIF動圖預覽 * @param queryid gif動圖的唯一標識 * @param path gif動圖儲存路徑 * @param time gif動圖間隔時間 * @param isCompress 圖片是否壓縮 * @param ratio 壓縮比例 * @return * @throws IOException */ public byte[] downloadGifByte(String queryid, String path, Integer time, Boolean isCompress, Integer ratio) throws IOException { //匹配mongo中filename滿足以queryid開頭的檔案 String regex = queryid + "([\\s\\S]*?)"; Query filename = Query.query(Criteria.where("filename").regex(regex)); GridFSFindIterable gridFSFiles = gridFsTemplate.find(filename); InputStream inputStream = null; //gif動圖建立的類 AnimatedGifEncoder animatedGifEncoder = new AnimatedGifEncoder(); animatedGifEncoder.setRepeat(0); //動圖儲存地址 String gifPath = path + "/" + queryid + ".gif"; //壓縮圖片儲存的地址 String saveFile = path + "/" + queryid + ".png"; animatedGifEncoder.start(gifPath); //gif動圖返回的二進位制流 byte[] fileBytes=null; for (GridFSFile gfsFile : gridFSFiles) { if (ObjectUtil.isNotNull(gfsFile)) { GridFSBucket gridFSBucket = GridFSBuckets.create(mongoDbFactory.getDb()); GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gfsFile.getObjectId()); //建立GridFsResource物件,獲取流 GridFsResource gridFsResource = new GridFsResource(gfsFile, gridFSDownloadStream); inputStream = gridFsResource.getInputStream(); BufferedImage image = null; if (!isCompress){ JPEGImageDecoder decoderFile = JPEGCodec.createJPEGDecoder(inputStream); image = decoderFile.decodeAsBufferedImage(); } else //壓縮圖片,壓縮圖不儲存到本地 { image = ImageHelper.compress(inputStream, new File(saveFile), ratio); } animatedGifEncoder.setDelay(time); animatedGifEncoder.addFrame(image); } } animatedGifEncoder.finish(); FileInputStream fileInputStream = new FileInputStream(gifPath); 轉化inputStream 為byte[] fileBytes= is2ByeteArray(fileInputStream); inputStream.close(); return fileBytes; } /** * 圖片預覽 * @param fileId * @param defaultStream * @return */ public byte[] downloadImageByte(String fileId) { byte[] fileBytes=null; try { // 查詢單個檔案 Query query = Query.query(Criteria.where("_id").is(fileId)); GridFSFile gfsFile = gridFsTemplate.findOne(query); InputStream inputStream = null; if (ObjectUtil.isNotNull(gfsFile)) { GridFSBucket gridFSBucket = GridFSBuckets.create(mongoDbFactory.getDb()); GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gfsFile.getObjectId()); //建立GridFsResource物件,獲取流 GridFsResource gridFsResource = new GridFsResource(gfsFile, gridFSDownloadStream); inputStream = gridFsResource.getInputStream(); } fileBytes= is2ByeteArray(inputStream); inputStream.close(); }catch (Exception e){ e.printStackTrace(); } return fileBytes; } //轉化inputStream 為byte[] public byte[] is2ByeteArray(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buff = new byte[100]; int rc = 0; while((rc=is.read(buff, 0, 100))>0) { baos.write(buff, 0, rc); } return baos.toByteArray(); } }
圖片壓縮工具類 ImageHelper
import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.WritableRaster; import java.io.*; /** * @author: Supermap·F * @descripition: 圖片壓縮 * @date: created in 11:05 2020/8/19 * @modify: Copyright (c) Supermap All Rights Reserved. */ public class ImageHelper { /** * 實現影象的等比縮放 * @param source * @param targetW * @param targetH * @return */ private static BufferedImage resize(BufferedImage source, int targetW, int targetH) { // targetW,targetH分別表示目標長和寬 int type = source.getType(); BufferedImage target = null; double sx = (double) targetW / source.getWidth(); double sy = (double) targetH / source.getHeight(); // 這裡想實現在targetW,targetH範圍內實現等比縮放。如果不需要等比縮放 // 則將下面的if else語句註釋即可 if (sx < sy) { sx = sy; targetW = (int) (sx * source.getWidth()); } else { sy = sx; targetH = (int) (sy * source.getHeight()); } if (type == BufferedImage.TYPE_CUSTOM) { // handmade ColorModel cm = source.getColorModel(); WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH); boolean alphaPremultiplied = cm.isAlphaPremultiplied(); target = new BufferedImage(cm, raster, alphaPremultiplied, null); } else target = new BufferedImage(targetW, targetH, type); Graphics2D g = target.createGraphics(); // smoother than exlax: g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy)); g.dispose(); return target; } /** * 實現影象的等比縮放和縮放後的擷取, 處理成功返回true, 否則返回false * @param inFilePath 要擷取檔案的路徑 * @param outFilePath 擷取後輸出的路徑 * @param width 要擷取寬度 * @param hight 要擷取的高度 * @throws Exception */ public static BufferedImage compress(String inFilePath, String outFilePath, int width, int hight) { BufferedImage ret = null; File file = new File(inFilePath); File saveFile = new File(outFilePath); InputStream in = null; try { in = new FileInputStream(file); ret = compress(in, saveFile, width, hight); } catch (FileNotFoundException e) { e.printStackTrace(); ret = ret; } finally{ if(null != in){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return ret; } /** * 實現影象的等比縮放和縮放後的擷取, 處理成功返回true, 否則返回false * @param in 要擷取檔案流 * @param saveFile 擷取後輸出的路徑 * @param width 要擷取寬度 * @param hight 要擷取的高度 * @throws Exception */ public static BufferedImage compress(InputStream in, File saveFile, int width, int hight) { // boolean ret = false; BufferedImage srcImage = null; BufferedImage resultImage = null; try { srcImage = ImageIO.read(in); } catch (IOException e) { e.printStackTrace(); return resultImage; } if (width > 0 || hight > 0) { // 原圖的大小 int sw = srcImage.getWidth(); int sh = srcImage.getHeight(); // 如果原影象的大小小於要縮放的影象大小,直接將要縮放的影象複製過去 if (sw > width && sh > hight) { srcImage = resize(srcImage, width, hight); } else { String fileName = saveFile.getName(); String formatName = fileName.substring(fileName .lastIndexOf('.') + 1); try { ImageIO.write(srcImage, formatName, saveFile); } catch (IOException e) { e.printStackTrace(); return resultImage; } return resultImage; } } // 縮放後的影象的寬和高 int w = srcImage.getWidth(); int h = srcImage.getHeight(); // 如果縮放後的影象和要求的影象寬度一樣,就對縮放的影象的高度進行擷取 if (w == width) { // 計算X軸座標 int x = 0; int y = h / 2 - hight / 2; try { resultImage = saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile); } catch (IOException e) { e.printStackTrace(); return resultImage; } } // 否則如果是縮放後的影象的高度和要求的影象高度一樣,就對縮放後的影象的寬度進行擷取 else if (h == hight) { // 計算X軸座標 int x = w / 2 - width / 2; int y = 0; try { resultImage = saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile); } catch (IOException e) { e.printStackTrace(); return resultImage; } } return resultImage; } /** * 實現影象的等比縮放和縮放後的擷取, 處理成功返回true, 否則返回false * @param in 圖片輸入流 * @param saveFile 壓縮後的圖片輸出流 * @param proportion 壓縮比 * @throws Exception */ public static BufferedImage compress(InputStream in, File saveFile, int proportion) { if(null == in || null == saveFile || proportion < 1){// 檢查引數有效性 //LoggerUtil.error(ImageHelper.class, "--invalid parameter, do nothing!"); return null; } BufferedImage srcImage = null; BufferedImage resultImage = null; try { srcImage = ImageIO.read(in); } catch (IOException e) { e.printStackTrace(); return resultImage; } // 原圖的大小 int width = srcImage.getWidth() / proportion; int hight = srcImage.getHeight() / proportion; srcImage = resize(srcImage, width, hight); // 縮放後的影象的寬和高 int w = srcImage.getWidth(); int h = srcImage.getHeight(); // 如果縮放後的影象和要求的影象寬度一樣,就對縮放的影象的高度進行擷取 if (w == width) { // 計算X軸座標 int x = 0; int y = h / 2 - hight / 2; try { resultImage = saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile); } catch (IOException e) { e.printStackTrace(); return resultImage; } } // 否則如果是縮放後的影象的高度和要求的影象高度一樣,就對縮放後的影象的寬度進行擷取 else if (h == hight) { // 計算X軸座標 int x = w / 2 - width / 2; int y = 0; try { resultImage = saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile); } catch (IOException e) { e.printStackTrace(); return resultImage; } } return resultImage; } /** * 實現縮放後的截圖 * @param image 縮放後的影象 * @param subImageBounds 要擷取的子圖的範圍 * @param subImageFile 要儲存的檔案 * @throws IOException */ private static BufferedImage saveSubImage(BufferedImage image, Rectangle subImageBounds, File subImageFile) throws IOException { if (subImageBounds.x < 0 || subImageBounds.y < 0 || subImageBounds.width - subImageBounds.x > image.getWidth() || subImageBounds.height - subImageBounds.y > image.getHeight()) { //LoggerUtil.error(ImageHelper.class, "Bad subimage bounds"); return null; } BufferedImage subImage = image.getSubimage(subImageBounds.x,subImageBounds.y, subImageBounds.width, subImageBounds.height); //暫時不用寫在伺服器本地 // String fileName = subImageFile.getName(); // String formatName = fileName.substring(fileName.lastIndexOf('.') + 1); // ImageIO.write(subImage, formatName, subImageFile); return image; } }
圖片預覽測試
百度圖片 - 動圖 (任何一個有圖片或者動圖的網站)
http://localhost:埠/******/image/{imageid}/preview.png?imageid=圖片存入mongo中返回的id&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJmaXNoZXIiLCJzY29wZSI6WyJzZXJ2ZXIiXSwiZXhwIjoxNTk3Nzc1MDkyLCJ1c2VyTmFtZSI6ImZpc2hlciIsInVzZXJJZCI6NTAsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iLCJQRVJfU1VQRVJBRE1
access_token= token資訊
替換圖片中的地址,就可以直接預覽圖片
參考連結:
圖片轉gif動圖
https://www.cnblogs.com/myjoan/p/4739102.html
https://blog.csdn.net/qq_35350654/article/details/83446258
圖片壓縮