巴拉巴拉
小魔仙

ImageUtil——Java对图片的一些操作

遇到一个简单的功能需求,web上传一张图片,但是这张图片可能很大(10m左右),预览的时候不需要查看原图。

1.从web端ajax上传图片

2.SpringMVC获取图片

3.服务端将图片上传(240px缩略图,1024px压缩图,原图)到阿里云OSS对象存储服务

  1. 本文章的主角:ImageUtil
  2. IO流的复用 InputStream复用
  3. OSS对象操作 AliyunOSS对象存储的操作
package com.againfly.util;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

public class ImageUtil {
    /**
     * byte数组转ByteArrayInputStream
     */
    public static InputStream parseInputStream(byte[] data){
        return new ByteArrayInputStream(data);
    }
    
    /**
     * byte数组转OutPutStream
     * @throws IOException 
     */
    public static OutputStream parseOutputStream(byte[] data) throws IOException{
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(data);
        out.flush();
        return out;
    }
    
    /**
     * 根据比例重新生成图片
     * 图片的最大边长不会超过 size
     * 若图片最大边不超过size,则不修改图片大小
     */
    public static byte[] resizeImage(InputStream is, int size, String format) throws IOException{
        BufferedInputStream bis = new BufferedInputStream(is);
        bis.mark(Integer.MAX_VALUE);
        BufferedImage prevImage = ImageIO.read(bis);
        bis.reset();
        double imageWidth = prevImage.getWidth();
        double imageHeight = prevImage.getHeight();
        
        int newWidth = 0;
        int newHeight = 0;
        
        if(imageHeight > size || imageWidth > size){
            boolean isHeight = true;
            if(imageWidth > imageHeight){
                isHeight = false;
            }
            double percent = 0;
            if(isHeight){
                percent = size / imageHeight;
            }else{
                percent = size / imageWidth;
            }
            
            newWidth = (int) (imageWidth * percent);
            newHeight = (int) (imageHeight * percent);
            
        }else{
            newWidth = (int) imageWidth;
            newHeight = (int) imageHeight;
        }
        
        return resizeImage(bis, newHeight, newWidth, format);
    }
    

    /**
     * 重新调整图片大小,并返回调整后图片文件的byte数组
     */
    public static byte[] resizeImage(InputStream is, int height, int width, String format) throws IOException{
        BufferedImage prevImage = ImageIO.read(is);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics graphics = image.createGraphics();
        graphics.drawImage(prevImage, 0, 0, width, height, null);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, format, os);
        byte[] out = os.toByteArray();
        os.flush();
        os.close();
        return out;
    }
    
    
    /**
     * 判断文件是否为图片
     */
    public static boolean isImage(File imageFile) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream(imageFile);
        boolean flag = isImage(fis);
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }
    
    /**
     * 判断文件是不是图片
     */
    public static boolean isImage(InputStream is) {
        Image img = null;
        try {
            img = ImageIO.read(is);
            if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            img = null;
        }
    }
    
    
    /**
     * 获取图片文件格式
     */
    public static ImageFormat imageFormat(File file) throws FileNotFoundException{
        FileInputStream fis = new FileInputStream(file);
        ImageFormat imgfmt = imageFormat(fis);
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgfmt;
    }
    
    

    /**
     * 获取图片文件的格式
     * @throws IOException 
     */
    public static ImageFormat imageFormat(InputStream is) {
        byte[] b = new byte[10];
        int l = -1;
        
        try {
            l = is.read(b);
        } catch (IOException e) {
            return ImageFormat.UNKNOW;
        }
        if (l == 10) {
            byte b0 = b[0];
            byte b1 = b[1];
            byte b2 = b[2];
            byte b3 = b[3];
            byte b6 = b[6];
            byte b7 = b[7];
            byte b8 = b[8];
            byte b9 = b[9];
            if (b0 == (byte) 'G' && b1 == (byte) 'I' && b2 == (byte) 'F') {
                return ImageFormat.GIF;
            } else if (b1 == (byte) 'P' && b2 == (byte) 'N' && b3 == (byte) 'G') {
                return ImageFormat.PNG;
            } else if (b6 == (byte) 'J' && b7 == (byte) 'F' && b8 == (byte) 'I' && b9 == (byte) 'F') {
                return ImageFormat.JPEG;
            } else {
                return ImageFormat.UNKNOW;
            }
        } else {
            return ImageFormat.UNKNOW;
        }
    }
    
    /**
     * 图片的格式枚举
     * jpg,png,gif,三种图片的格式名,格式后缀,以及Http的Header:Content-Type信息
     */
    public enum ImageFormat{
        JPEG("jpg", ".jpg", "image/jpeg"),
        PNG("png", ".png", "image/png"),
        GIF("gif", ".gif", "image/gif"),
        UNKNOW("jpg", ".jpg", "image/jpeg");
        
        private String format;
        private String suffix;
        private String contentType;

        private ImageFormat(String format, String suffix, String contentType) {
            this.format = format;
            this.suffix = suffix;
            this.contentType = contentType;
        }
        
        public String getFormat() {
            return format;
        }
        public String getSuffix() {
            return suffix;
        }
        public String getContentType() {
            return contentType;
        }
    }
}

html & js 部分

<form id="post_img" action= "http://localhost:8080/cfJAX_RS/rest/file/upload" method= "post" enctype ="multipart/form-data">  
    <input id="image_file" type="file" name="file" />
    <input name="id" value="1212"/>
    <input type="button" onclick="clickBtn()" value="上传">
</form>

=======================================================================

function clickBtn(){
    filepath=$("#image_file").val();
    var extStart = filepath.lastIndexOf(".");
    var ext = filepath.substring(extStart,filepath.length).toUpperCase();
    if(ext != ".BMP" && ext != ".PNG" && ext != ".GIF" && ext != ".JPG" && ext != ".JPEG"){
        alert("图片限于png,gif,jpeg,jpg格式");
        return;
    }
    
     var formData = new FormData($("#post_img")[0]);  
     $.ajax({  
          url: 'img/post_file' ,  
          type: 'POST',
          data: formData,  
          async: true,  
          cache: false,  
          contentType: false,  
          processData: false,  
          success: function (returndata) {  
              alert(returndata);  
          },  
          error: function (returndata) {  
              alert(returndata);
          }
     });  
}

java后台部分

@RequestMapping("/post_file")
public @ResponseBody boolean postFile(@RequestBody MultipartFile file,int id) throws Exception{
    return service.postFile(file, id);
}
@Resource
private Aliyun aliyun;


public boolean postFile(MultipartFile file, int id) throws Exception{
    long size = file.getSize();
    //文件不能大于10mb
    if(1024 * 1024 * 10 < size){
        return false;
    }
    
    Map<String,Object> dataMap = new HashMap<>();
    
    System.out.println(id);
    
    System.out.println(file.getInputStream().getClass().getName());
    //进行缓存
    BufferedInputStream is = new BufferedInputStream(file.getInputStream());
    is.mark(Integer.MAX_VALUE);
    
    boolean image = ImageUtil.isImage(is);
    is.reset(); 
    if(!image){
        return false;
    }
    
    ImageFormat imageFormat = ImageUtil.imageFormat(is);
    is.reset();
    
    String fileName = UUID.randomUUID().toString().replaceAll("-", "");
    
    String perfix = "cust_contract";
    
    String suffix = imageFormat.getSuffix();
    
    Timestamp now = new Timestamp(System.currentTimeMillis());
    
    {//上传缩略图,最大边长240px
        String key = perfix + "/" + fileName + "_xs" + suffix;
        byte[] data = ImageUtil.resizeImage(is, 240, imageFormat.getFormat());
        is.reset();
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        String sxEndPoint = aliyun.OSSPutObject(key, bis);
        bis.close();
        dataMap.put("sxEndPoint", sxEndPoint);
        System.out.println(sxEndPoint);
    }
    
    {//上传压制图,最大边长1024px
        String key = perfix + "/" + fileName + "_lg" + suffix;
        byte[] data = ImageUtil.resizeImage(is, 1024, imageFormat.getFormat());
        is.reset();
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        String lgEndPoint = aliyun.OSSPutObject(key, bis);
        bis.close();
        System.out.println(lgEndPoint);
        dataMap.put("lgEndPoint", lgEndPoint);
    }
    
    {//上传原图
        String key = perfix + "/" + fileName + suffix;
        String originalEndPoint = aliyun.OSSPutObject(key, is);
        System.out.println(originalEndPoint);
    }
    
    is.close();
    
    return true;
}

=================补充内容=================

给图片叠加文字或者其他内容:

package com.againfly.img;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;

import javax.imageio.ImageIO;

public class ImgTest{
    public static void main(String[] args) throws Exception {
        //读背景文件
        Image src = ImageIO.read(new File("D:\\1.JPG"));
        BufferedImage image = new BufferedImage(src.getWidth(null), src.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        
        g.drawImage(src, 0, 0, null);
        
        String str = "为了保护世界和平";
        AttributedString ats = new AttributedString(str); 
        Font f = new Font("", Font.PLAIN, 16);
        ats.addAttribute(TextAttribute.FONT, f, 0, str.length());
        AttributedCharacterIterator iter = ats.getIterator(); 
        
        //设置文字颜色
        /*
         * 参数值是颜色的10进制
         * 0是黑色
         * 65535是白色
         * 也可以写成0xFFFFFF 16进制的方式
         */
        g.setColor(new Color(0xFFFFFF));
        
        g.drawString(iter, 110, 60);
        g.dispose();
        
        //输出文件
        ImageIO.write(image, "png", new FileOutputStream(new File("D:\\2.JPG")));
    }
}

 

赞(0) 打赏
如果文章对你有帮助,欢迎你来评价反馈。AgainFly » ImageUtil——Java对图片的一些操作

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  • Q Q(选填)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏