layer.photos 查看本地图片,并实现缩放和旋转功能
公司用了layui這個框架,需要用到展示圖片這個功能,千辛萬苦終于實現啦!!!記錄一下
后端:
? ?1.controller(我這邊是直接從前端傳遞來圖片地址)
@Log(title = "查看圖片", businessType = BusinessType.IMPORT)@GetMapping("/imgView")@ResponseBodypublic String imgView(@RequestParam(value = "path", required = false) String path) throws Exception{return xxxxxInfoService.getImgView(path);}2.service
/**、* 獲取圖片* @param path* @return*/public String getImgView(String path);3.impl? (是jpg或者png 等圖片就可以直接展示,因為還有tif 圖片,前端無法直接展示,所以需要處理一下)
application.yml
xxxPath:D:\upload\ xxxTifPath:D:\uploadTif\ package com.ruoyi.common.utils.bean;import lombok.Data; import org.springframework.util.ObjectUtils;import java.util.List;/*** layUi圖片查看*/ @Data public class PhotosBean {/** 標題*/private String title;/** 相冊ID*/private int id;//初始顯示的圖片序號,默認0private int start;private List<PhotosInfo> data;public int getStart() {return ObjectUtils.isEmpty(start)? 0 : start;} } package com.ruoyi.common.utils.bean;import lombok.Data;/*** layUi 圖片集合*/ @Data public class PhotosInfo {/** 圖片名*/private String alt;/** 圖片id*/private Integer pid;/** 原圖地址*/private String src;/** 圖片在服務器的真實路徑*/private String sourcePath; } package com.ruoyi.system.eunm;/*** 本地地址pool*/ public interface localPathPool {/** 類型*/String TIF = ".tif";String JPG = ".jpg";String LOCAL_IMG_PATH = "/localImgPath/";String LOCAL_TIF_IMG_PATH = "/localTifImgPath/"; }//---------------------------------------------------------------------- package com.ruoyi.system.service.impl;import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List;import com.alibaba.fastjson.JSON; import com.ruoyi.common.config.ServerConfig; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.bean.PhotosBean; import com.ruoyi.common.utils.bean.PhotosInfo; import com.ruoyi.common.utils.file.FileUtils; import com.ruoyi.system.domain.YhSatelliteInfo; import com.ruoyi.system.eunm.localPathPool; import com.ruoyi.system.mapper.YhSatelliteInfoMapper; import com.ruoyi.system.service.IYhSatelliteInfoService; import com.ruoyi.common.core.text.Convert; import com.sun.org.slf4j.internal.Logger; import com.sun.org.slf4j.internal.LoggerFactory;import javax.imageio.ImageIO; import javax.imageio.stream.FileImageInputStream;@Service public class xxxxInfoServiceImpl implements xxxxInfoService {private static final Logger log = LoggerFactory.getLogger(xxxxInfoServiceImpl.class);@Autowiredprivate ServerConfig serverConfig;@Value("${xxxPath}")private String imgPath;@Value("${xxxTifPath}")private String tifImgPath;@Overridepublic String getImgView(String dirName) {try {if(ObjectUtils.isEmpty(imgPath)){return null;}PhotosBean bean = new PhotosBean();bean.setTitle("查看圖片");bean.setId(0);bean.setData(getDirPhotos(dirName));return JSON.toJSONString(bean);}catch (Exception e){throw new RuntimeException("獲取圖片失敗:原因是:"+e);}}/*** 獲取文件夾下圖片* @param dirName* @return*/public List<PhotosInfo> getDirPhotos(String dirName){File file = FileUtils.getCheckDir(imgPath + dirName);if(null != file){File[] files = file.listFiles();List<PhotosInfo> list = new ArrayList<>(files.length);for (int i = 0; i < files.length; i++) {File fi = files[i];PhotosInfo photosInfo = new PhotosInfo();/** 配置文件的本地映射真實路徑*/String localImg = localPathPool.LOCAL_IMG_PATH + dirName + File.separator + fi.getName();/** 文件下載路徑*/photosInfo.setSourcePath(serverConfig.getUrl() + localImg);photosInfo.setPid(i);photosInfo.setAlt(fi.getName());photosInfo.setSrc(localImg);/** 如果是tif就需要更改展示路徑*/String type = fi.getName().substring(fi.getName().lastIndexOf("."));if(localPathPool.TIF.equals(type.toLowerCase())){/** 獲取名稱*/String sendName = fi.getName().substring(0,fi.getName().lastIndexOf("."));String viewPath = localPathPool.LOCAL_TIF_IMG_PATH + dirName + File.separator + sendName + localPathPool.JPG;photosInfo.setSrc(viewPath);try {tifToJpg(fi,tifImgPath + dirName,sendName);}catch (Exception e){log.error(fi.getPath()+"轉換失敗!");/** 轉換失敗默認讓他查看一張*/photosInfo.setSrc(localPathPool.LOCAL_IMG_PATH + "error" + File.separator + "errimg.jpg");}}list.add(photosInfo);}return list;}return null;}public void tifToJpg(File source, String sendDir,String sendName) throws Exception {String sendPath = sendDir + File.separator + sendName + localPathPool.JPG;log.info("------------------------需要轉換的地址是------------------------:" + sendPath);new File(sendDir).mkdirs();if (new File(sendPath).exists()) {return;}oneMakeSingleTif(source,sendPath);}public void oneMakeSingleTif(File fTiff,String sendPath) throws Exception {FileImageInputStream fis = null;try {TIFFImageReaderSpi tiffImageReaderSpi = new TIFFImageReaderSpi();TIFFImageReader tiffImageReader = new TIFFImageReader(tiffImageReaderSpi);fis = new FileImageInputStream(fTiff);tiffImageReader.setInput(fis);BufferedImage bi = tiffImageReader.read(0);ImageIO.write(bi,"jpg",new File(sendPath));} catch (Exception e) {throw new IOException("TIF轉JPG失敗!"+e);} finally {if (fis != null) {try {fis.flush();fis.close();} catch (IOException e) {e.printStackTrace();}}}} }4.最后記得配置映射器(我是用的若依不分離版本的框架,如果使用的是前后端分離的,記得在negix里面配置映射路徑)
package com.ruoyi.web.core.config;import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configuration public class ImgPathConfig extends WebMvcConfigurerAdapter {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {//addResourceHandler是指定的虛擬路徑,addResourceLocations是自己的物理路徑,registry.addResourceHandler("/localImgPath/**").addResourceLocations("file:/D:/upload/");registry.addResourceHandler("/localTifImgPath/**").addResourceLocations("file:/D:/uploadTif/");super.addResourceHandlers(registry);} }前段:
前臺的圖片展示,由于暫時未找到該插件自帶的縮放和旋轉功能,只能自己實現了
功能實現參考了 這位大佬的博客?layer.photos放大縮小以及旋轉_qq_35031260的博客-CSDN博客_layer.photos放大layer.photos放大縮小以及旋轉由于在網上搜到的旋轉都多少有些問題,要么是旋轉后圖片轉底層的背景大小不改變導致圖片展示不全,要么是連背景一起旋轉用起來很不方便,所以我把他調整成了旋轉圖片并且根據圖片旋轉后的長寬調整背景層的長寬。事先準備替換layer.js中最后一行的contentcontent: '<input type="hidden" id="current"><div class="layui-layer-phimg"><img id="imglayerhttps://blog.csdn.net/qq_35031260/article/details/118786216
?我在此基礎上更改了一下
<!DOCTYPE html> <html lang="zh" xmlns:th="http://www.thymeleaf.org"> <head><th:block th:include="include :: header('需求列表')"/> </head> <body class="gray-bg"> <div class="container-div"><div class="row"></div> </div><th:block th:include="include :: footer"/> <script th:inline="javascript">var prefix = ctx + "system/info";$(function () {var options = {url: prefix + "/list",onClickRow: onClickRow, //此處為單擊行調用的方法onLoadSuccess: onLoadSuccess,columns: [{checkbox: true},{field: 'id',title: '',visible: false},{class: 'W80',field: 'imgPath',title: '查看圖片',align: 'center',events: viewImg,formatter: function (value, row, index) {if (value != null) {return ['<a class="searchImg">查看圖片</a>',].join('');}}},{class: 'W50',field: 'imgCount',title: '圖片數量',align: 'center'},]};$.table.init(options);});function onClickRow(row, $element) {$element[0].firstElementChild.firstElementChild.click();}function onLoadSuccess(data) {let sumImgCount = 0;let rows = data.rows;for (let i = 0; i < rows.length; i++) {sumImgCount += rows[i].imgCount;}$("#imgSum").html(sumImgCount)}window.viewImg = {'click .searchImg': function (e, value, row, index) {viewImgs(value);}};var num = 0;/** 展示圖片*/function viewImgs(value) {$.modal.loading("正在加載請稍等....");if (null == value || '' == value) {return false;}$.getJSON(prefix + "/imgView?path=" + value, function (json) {layer.photos({photos: json,shadeClose: false,closeBtn: 2,tab: function () {$.modal.closeLoading();/** 自定義旋轉和關閉按鈕*/let str = '<button type="button" style="margin-left: 10px" class="btn btn-primary" onclick="rotateImg()">旋轉</button>';str += '<button type="button" style="margin-left: 70px" class="btn btn-warning layui-layer-close layui-layer-close2">關閉</button>';$(".layui-layer-phimg .layui-layer-imgsee .layui-layer-imgbar .layui-layer-imgtit").append(str);/** 去除原來的關閉按鈕*/$(".layui-layer.layui-layer-page.layui-layer-photos .layui-layer-setwin").css("display", "none");num = 0;/** 每次翻頁都初始化*/let layerPhotos = $(".layui-layer.layui-layer-page.layui-layer-photos #layui-layer-photos");let phImg = $(".layui-layer.layui-layer-page.layui-layer-photos #layui-layer-photos .layui-layer-phimg");let image = $(".layui-layer.layui-layer-page.layui-layer-photos #layui-layer-photos .layui-layer-phimg img");phImg.css('width', layerPhotos.width())phImg.css('height', layerPhotos.height())image.css('width', "100%");image.css('height', "100%");},anim: 0});});}function rotateImg() {/** 先將圖片外層邊框大小設置為最外面邊框大小,因為圖片實際大小與父邊框大小不一致,結果導致被裁剪了,這可能是作者沒注意*/let layerPhotos = $(".layui-layer.layui-layer-page.layui-layer-photos #layui-layer-photos");let phImg = $(".layui-layer.layui-layer-page.layui-layer-photos #layui-layer-photos .layui-layer-phimg");let image = $(".layui-layer.layui-layer-page.layui-layer-photos #layui-layer-photos .layui-layer-phimg img");image.css('width', "100%");image.css('height', "100%");num = (num + 90) % 360;/** 這里只旋轉圖片,不旋轉div*/image.css('transform', 'rotate(' + num + 'deg)');if (num == 90 || 270 == num) {/** 該操作只針對寬度大于高度的圖片*/if (image.width() > image.height()) {/** 圖片進行旋轉時 寬度就等于外邊框的高度,讓圖片等比例所發 */image.css('height', phImg.height() / 1.5)image.css('width', phImg.height())/** 因為不知道的原因旋轉后會偏移,所以需要再次計算一下*/image.css('margin-top', (image.width() - image.height()) / 2)}} else {image.css('width', phImg.width())image.css('height', "100%")image.css('margin-top', '0px');}changeImgSize(layerPhotos, phImg);}/** 縮放*/$(document).on("mousewheel DOMMouseScroll", ".layui-layer-phimg", function (e) {var delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) || // chrome & ie(e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1)); // firefoxlet layerPhotos = $(".layui-layer.layui-layer-page.layui-layer-photos #layui-layer-photos");layerPhotos.css("overflow", "visible")let phimg = $(".layui-layer.layui-layer-page.layui-layer-photos #layui-layer-photos .layui-layer-phimg");var h = phimg.height();var w = phimg.width();if (delta > 0) {h = h * 1.05;w = w * 1.05;} else if (delta < 0) {if (h > 100) {h = h * 0.95;w = w * 0.95;}}phimg.height(h);phimg.width(w);let img = $(".layui-layer.layui-layer-page.layui-layer-photos #layui-layer-photos .layui-layer-phimg img");changeImgSize(layerPhotos, phimg);img.css('width', "100%");img.css('height', "100%");});/** 縮放后得重新計算一次偏移量*/function changeImgSize(layerPhotos, val2) {if (layerPhotos.width() > val2.width()) {let leftSize = (layerPhotos.width() - val2.width()) / 2;val2.css("margin-left", leftSize);let heightSize = (layerPhotos.height() - val2.height()) / 2;val2.css("margin-top", heightSize);} else {val2.css("margin-left", 0);val2.css("margin-top", 0);}val2.css('position', "fixed");} </script> </body> </html>另外還提供了下載按鈕,不過我是通過更改layer.min.js實現的
? ? 效果圖展示
?
?
總結
以上是生活随笔為你收集整理的layer.photos 查看本地图片,并实现缩放和旋转功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 美团codeM资格赛 优惠券
- 下一篇: android 内存6g 8g 12g,