JAVA上传图像时图像处理的基本方法

来源:互联网 发布:蛇口招商网络宽带上班 编辑:程序博客网 时间:2024/06/04 18:40


一,form表单类型

<form id="xxForm" action="xx.htm" method="post" enctype ="multipart/form-data" >

则请求头含有:

formdata-----------------------------14471729621574Content-Disposition: form-data; name="Filedata"; filename="11.jpg"Content-Type: image/jpeg

二,文件大小控制(3M)

MultipartFile file = ((MultipartHttpServletRequest) request).getFile("Filedata");if (file == null || file.getSize() >= 3 * 1024 * 1024) {    showErrorMsg();}


三,文件后缀名控制

直接使用MultipartFile file 的getOriginalFilename()方法,获取到的中文名称可能是乱码。建议单独传参fileName

String suffix = StringUtil.substringAfterLast(fileName, ".").toLowerCase();        if (!suffix.matches(IMAGE_TYPE)) {           showErrorMsg();       }private static final String                       IMAGE_TYPE             = "(jpg|jpeg|png)";


四,文件安全检查

以上三种类型都应该可以正常转换为jpg文件

try {            src = ImageIO.read(infile.getInputStream());        } catch (IOException e) {            throw e;        }        ByteArrayOutputStream baos = new ByteArrayOutputStream();ImageIO.write(src, "jpg", baos);


五,图片裁剪,缩放

/**     * 裁剪图片     *     * @param in     * @param out     * @param format (jpg,jpeg,png)     * @param x 截取后的x坐标     * @param y 截取后的y坐标     * @param width 截取后的宽度     * @param height 截取后的高度     * @param orgWidth 图片宽度     * @param orgHeight 图片高度     */    public static void clipPic(ByteArrayInputStream in, ByteArrayOutputStream out, String format,                               int x, int y, int width, int height, int orgWidth, int orgHeight) {        try {            LoggerUtil.info(LOGGER, "[PicCompress]开始裁减图片! ");            BufferedImage tag = ImageIO.read(in);            BufferedImage oute = null;            int sourceWidth = tag.getWidth();            int sourceHeight = tag.getHeight();            if (width >= orgWidth && height >= orgHeight) {                oute = tag.getSubimage(0, 0, sourceWidth, sourceHeight);            } else {                double rateW = (double) sourceWidth / (double) orgWidth;                double rateH = (double) sourceHeight / (double) orgHeight;                int targetWidth = (int) ((width < orgWidth ? width : orgWidth) * rateW);                int targetHeight = (int) ((height < orgHeight ? height : orgHeight) * rateH);                int targetX = (int) (x * rateW);                int targetY = (int) (y * rateH);                oute = tag.getSubimage(targetX, targetY, targetWidth, targetHeight);            }            //保存新图片              ImageIO.write(oute, format, out);        } catch (IOException e) {            LoggerUtil.warn(LOGGER, "[PicCompress]裁减图片失败! ", e);        }    }

六,图片压缩

public static void compressPic(ByteArrayInputStream in, ByteArrayOutputStream out,                                   String format, int size, int limitSize) {        try {            BufferedImage img = ImageIO.read(in);            double rate = (double) limitSize / (double) size;            int width = (int) (img.getWidth() * rate);            int height = (int) (img.getHeight() * rate);            BufferedImage tag = null;            if (StringUtil.equals(format, "png")) {                tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);            } else {                tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);            }            tag.getGraphics().drawImage(img.getScaledInstance(width, height, Image.SCALE_SMOOTH),                0, 0, null);            //保存新图片              ImageIO.write(tag, format, out);        } catch (IOException e) {            LoggerUtil.warn(LOGGER, "[PicCompress]压缩图片大小失败! ", e);        }    }

七,其他流处理工具

转换

/**     * 从输入流读取内容, 写入到输出流中.  使用指定大小的缓冲区.     *     * @param in 输入流     * @param out 输出流     * @param bufferSize 缓冲区大小(字节数)     *     * @throws IOException 输入输出异常     */    public static void io(InputStream in, OutputStream out, int bufferSize)            throws IOException {        if (bufferSize == -1) {            bufferSize = DEFAULT_BUFFER_SIZE;        }        byte[] buffer = new byte[bufferSize];        int    amount;        while ((amount = in.read(buffer)) >= 0) {            out.write(buffer, 0, amount);        }    }private static final int DEFAULT_BUFFER_SIZE = 8192;

关闭,应当在finally中执行

/**     * 安全的关闭流     * @param <T>     * @param stream     */    public static <T extends Closeable> void closeStreamSafely(T stream) {        if (stream == null) {            return;        }        try {            stream.close();        } catch (IOException e) {            //ignore        }    }

同步化的输出流

/**     * 同步化的输出流包裹器.     */    private static class SynchronizedOutputStream extends OutputStream {        private OutputStream out;        private Object       lock;        SynchronizedOutputStream(OutputStream out) {            this(out, out);        }        SynchronizedOutputStream(OutputStream out, Object lock) {            this.out      = out;            this.lock     = lock;        }        public void write(int datum) throws IOException {            synchronized (lock) {                out.write(datum);            }        }        public void write(byte[] data) throws IOException {            synchronized (lock) {                out.write(data);            }        }        public void write(byte[] data, int offset, int length)                throws IOException {            synchronized (lock) {                out.write(data, offset, length);            }        }        public void flush() throws IOException {            synchronized (lock) {                out.flush();            }        }        public void close() throws IOException {            synchronized (lock) {                out.close();            }        }    }








0 0