JAVAアップロード時の画像処理の基本方法

6396 ワード

一、formフォームタイプ

要求ヘッダには次のものが含まれます.formdata -----------------------------14471729621574 Content-Disposition: form-data; name="Filedata"; filename="11.jpg" Content-Type: image/jpeg
二、ファイルサイズ制御(3 M)
MultipartFile file = ((MultipartHttpServletRequest) request).getFile("Filedata");

if (file == null || file.getSize() >= 3 * 1024 * 1024) {

    showErrorMsg();

}

三、ファイル接尾辞名制御
MultipartFile fileのgetOriginalFilename()メソッドを直接使用すると、取得した中国語名が文字化けしている可能性があります.単独での参照を推奨するfile Name
String suffix = StringUtil.substringAfterLast(fileName, ".").toLowerCase();
        if (!suffix.matches(IMAGE_TYPE)) {

           showErrorMsg();

       }

private static final String                       IMAGE_TYPE             = "(jpg|jpeg|png)";

四、書類安全検査
以上の3種類は正常に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();
            }
        }
    }