公司用了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 查看本地图片,并实现缩放和旋转功能相关推荐

  1. 基于PyQt5实现查看本地图片功能

    基于Python和PyQt5实现查看本地图片功能 通过点击按钮打开本地文件夹选择图片进行显示,也可扩展选择图片路径后自动获取图片数量及相关信息·实现翻页.轮播图等效果和功能. 效果 sample_sh ...

  2. 微信小程序怎么实现 图片按住一角缩放、旋转、拖拽

    微信小程序怎么实现 图片按住一角缩放.旋转.拖拽 图片一角可以加个小图片,按住来操作 利用movable-view.movable-area 可以实现拖拽缩放.不好旋转 是不是可以利用canvas绘图 ...

  3. Android中实现图片平移、缩放、旋转同步进行

    转载请注明转自:noyet12的博客 博客原址:http://blog.csdn.net/u012975705/article/details/49797911 源码下载地址: (github)htt ...

  4. web手势库AlloyFinger运用( 控制CANVAS中图片移动、缩放、旋转) - 可编辑图片指定区域位置

    注: 苹果手机升级IOS14.1系统后,出现图片写入不了CANVAS画布问题 解决方法:alloy_paper.js 文件查找代码: this.img.crossOrigin = "Anon ...

  5. layer.photos 相册(图片查看器)实现缩放

    2019年4月12日 layer版本 layer-v3.1.1 layer.photos 方法在使用过程中发现没有通过鼠标中键(滚轴)实现图片缩放功,故通过搜索引擎找到如下方法 需要引用 jquery ...

  6. layer.photos 点击图片放大查看

    $("body").on("click",".imgs img",(e) => {layer.photos({photos: { &q ...

  7. vue-preview动态获取图片宽高并增加旋转功能

    vue-preview是一个常用的图片查看器,微博网页版就是用的这个插件: 我在项目中也用过这个插件,总体来说,还是比较满意.但是缺少一个图片旋转功能. 安装使用 第一步:安装 npm i vue-p ...

  8. Mac怎么查看本地图片路径

    Mac不如Win那样有清晰的分盘,可以直观定位某张图片的本地地址,那么怎么知道一张图片在Mac文件中的绝对路径呢? 很简单! 1:打开终端 2:将图片拖入终端 3:复制终端中生成的地址即可食用

  9. 手机端本地图片或者拍照的上传功能

    原文连接 https://blog.csdn.net/m0_37852904/article/details/78550136 ------------------------------------ ...

最新文章

  1. matplotlib可视化时间序列数据、并高亮时间序列中的指定区域(Highlight a Region of Time-Series Plot with Matplotlib)
  2. curl取跳转地址 php_用PHP如何实现解析抖音无水印视频
  3. rabbitmq消息重回队列
  4. MySQLi学习笔记 :一 1. 数据库的基本概念 2. MySQL数据库软件 安装-- 卸载--. 配置 3. SQL
  5. LinkedIn应用开发系列(三) --认证Request token
  6. linux系统安装花生壳
  7. 【转】音视频工程中VGA线材的选材技巧
  8. tabbaritem 图片太大解决方案
  9. “一年前,我来到国企搞IT”
  10. Rod-cutting(动态规划)
  11. 芯片市场混乱,教你几招辨别真假
  12. 使用NGINX发布DEM切片
  13. 中兴echat_中兴通讯助力公共安全行业数字化转型
  14. Android 全景视频播放器(VR视频播放器探索二)
  15. 手机如何借用笔记本网络上网
  16. linux为什么不能配置网络打印机,linux配置网络打印机
  17. ubuntu16.04的HDMI没有输出不能外接显示器
  18. 【板栗糖GIS】为什么内网穿透过的地址出现Tunnel not found
  19. 让Windows 时间与Internet 时间服务器同步
  20. category.php ecshop,category.php

热门文章

  1. STM32CUBE+自平衡车实践篇3.4-STM32cueb配置编码器+车轮速度测量代码实现
  2. /* 商人过河的问题 假如有三个商人各带一个随从要过河。 只有一条船得需要他们划每次只能坐两个人,条件是任何一岸的随从多于商人时随从就会抢劫商人。 请问这三个商人怎样才能安全过河? */...
  3. python识别文字坐标_【Python 教程】使用 Python 和大漠插件进行文字识别
  4. C#项目解决方案管理器中将*.Designer.cs文件放到*.cs文件下
  5. 从COVID-19大流行中汲取哪些教训?10种方法帮CIO预防下一次危机
  6. html img 拉伸,图片因img标签拉伸的处理办法
  7. 深度解读AMBA、AHB、APB、AXI总线
  8. perf常用命令(perf top perf record perf stat)
  9. c++switch语言,C++ switch语句
  10. 小程序地理位置接口wx.getLocation申请审核解决方法(详细说明及避坑)