栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现png转ico,支持尺寸选择

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现png转ico,支持尺寸选择

1. 网站logo

favicon.ico图标是网站的缩略标志,可以显示在浏览器标签、地址栏左边和收藏夹,是展示网站个性的缩略logo标志,也可以说是网站头像
常用的favicon.ico图标有3种16×16(推荐)、32×32、48×48

网页引用



在线制作ico   https://www.easyicon.net/covert/
2. Java实现png转ico

pom依赖
参考 https://github.com/HuBoZhi/image4j,本地打包image4j



    net.sf
    image4j
    1.0.0


 

    com.mortennobel
    java-image-scaling
    0.8.6

实体类ImageEntity

@Data
public class ImageEntity {
    
    private String size;
    
    private String imgType;
}

ImageService类

package com.cmbchina.file.service;

import com.cmbchina.base.exception.BizException;
import com.cmbchina.file.base.ImageEntity;
import com.mortennobel.imagescaling.AdvancedResizeOp;
import com.mortennobel.imagescaling.ResampleOp;
import lombok.extern.slf4j.Slf4j;
import net.sf.image4j.use.Image4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;
import java.util.UUID;


@Slf4j
@Service
public class ImageService {

    public String imgToICO(MultipartFile file, ImageEntity imageEntity) throws IOException {
        String originalFilename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        //保存到本地
        String fullName = FilenameUtils.concat(SystemUtils.JAVA_IO_TMPDIR, originalFilename);
        log.info("保存上传图片到本地:{}", fullName);
        File pngFile = new File(fullName);
        OutputStream out = new FileOutputStream(pngFile);
        IOUtils.write(IOUtils.toByteArray(inputStream), out);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(inputStream);

        //修改尺寸
        String ext = FilenameUtils.getExtension(originalFilename).toLowerCase();
        File resizeFile = new File(FilenameUtils.concat(SystemUtils.JAVA_IO_TMPDIR, UUID.randomUUID().toString() + "." + ext));
        String size = imageEntity.getSize();
        int width = 0;
        if(size.contains("x")){
            width = Integer.valueOf(size.substring(0, size.indexOf("x")));
        }else if(size.contains("X")){
            width = Integer.valueOf(size.substring(0, size.indexOf("X")));
        }else{
            width = Integer.valueOf(size);
        }
        resize(pngFile, resizeFile, width, width, ext);

        log.info("保存上传图片修改后的尺寸{}, 到本地:{}", size, fullName);

        //png/jpg 转 ico
        String icoPath = "D:/upload/" + UUID.randomUUID().toString() + ".ico";
        Image4j.Convert(resizeFile.getAbsolutePath(), icoPath);
        log.info("上传图片转换为ico到本地{}", icoPath);

        String base64 = Base64.getEncoder().encodeToString(IOUtils.toByteArray(new FileInputStream(icoPath)));

        //删除
        pngFile.delete();
        resizeFile.delete();
        new File(icoPath).delete();
        log.info("删除本地保存的上传图片");
        log.info("删除本地保存的修改后的尺寸的上传图片");
        log.info("删除本地保存的ico");

        return base64;
    }

    
    public static void resize(File originalFile, File resizedFile, int newWidth, int newHeight, String formatName) {
        try {
            BufferedImage inputBufImage = ImageIO.read(originalFile);
            ResampleOp resampleOp = new ResampleOp(newWidth, newHeight);// 转换
            resampleOp.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.Oversharpened);
            BufferedImage rescaledTomato = resampleOp.filter(inputBufImage,null);
            ImageIO.write(rescaledTomato, formatName, resizedFile);
        } catch (IOException e) {
            throw new BizException("图片尺寸缩放异常", e);
        }
    }
}

ImageControler类

@Slf4j
@Validated
@RestController
@RequestMapping("/img")
public class ImageController {
    @Autowired
    private ImageService imageService;

    
    @PostMapping("/upload")
    public RetResult upload(@RequestParam MultipartFile file, ImageEntity imageEntity) {
        if (file.isEmpty()) {
            throw new BizException("上传文件为空");
        }
        String targetFileName = file.getOriginalFilename();
        if (!"jpg".equalsIgnoreCase(FilenameUtils.getExtension(targetFileName)) && !"png".equalsIgnoreCase(FilenameUtils.getExtension(targetFileName))) {
            throw new BizException("上传图片格式必须是jpg或者png");
        }
        try {
            String base64 = imageService.imgToICO(file, imageEntity);
            return RetModel.ok().setData(ViewObject.content(base64));
        } catch (IOException e) {
            throw new BizException("上传文件异常");
        }
    }


    
    @GetMapping("/download")
    public void download(HttpServletResponse response, @NotBlank(message = "文件路径不能为空") String filePath) throws IOException {
        InputStream inputStream = new FileInputStream(filePath);
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = IOUtils.toByteArray(inputStream);
        outputStream.write(bytes);
    }
}

3. 前端测试

上传下载文件表单

 

目标尺寸:

原始图片(不超过200kb):


js脚本

    var base64 = "";

    function submitFormFn(){
        if($('input[name=file]')[0].files[0] === undefined){
            return
        }
        var formData = new FormData();
        formData.append("size", $('[name=size]').find("option:selected").val());
        formData.append("file", $('input[name=file]')[0].files[0]);
        $.ajax({
            url: "http://localhost:8080/img/upload",
            type: "POST",
            data: formData,
            contentType: false, //必须false才会自动加上正确的Content-Type
            processData: false, // 必须false才会避开jQuery对 formdata 的默认处理,  XMLHttpRequest会对 formdata 进行正确的处理
            dataType: "json",
            success: function (data) {
                if (data.retCode === '0000') {
                    base64 = data.result.content
                    $('#showImg').prop('src', "data:image/png;base64," + base64)
                    $('#showDiv').show()
                }
            },
            error: function () {
                alert("上传失败!");
            }
        });
    }

    //a标签方式下载
    function downloadFn(){
        if(!base64){
            return
        }
        let a = document.createElement('a');
        a.download = new Date().getTime() + '.ico';
        a.href = "data:image/png;base64," + base64;
        $("body").append(a);    // 修复firefox中无法触发click
        a.click();
        $(a).remove();

    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/894935.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号