Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
change compression level without losing the metadata of a jpg file
(ns sandbox.compress-jpg
(meta {:description "change compression level without losing the metadata of a jpg file"
:url "http://blog.carsoncheng.ca/2011/02/how-to-change-jpeg-compression-in.html"})
(:require clojure.java.io)
(:import [javax.imageio IIOImage ImageIO]
[javax.imageio.plugins.jpeg JPEGImageWriteParam]))
(defn compress-jpg [inputFile outputFile compressionQuality]
(let [image-reader (.next (ImageIO/getImageReadersByFormatName "jpg"))
image-writer (.next (ImageIO/getImageWritersByFormatName "jpg"))]
(try
(with-open [image-input-stream (ImageIO/createImageInputStream
(clojure.java.io/file inputFile))
image-output-stream (ImageIO/createImageOutputStream
(clojure.java.io/file outputFile))]
(.setInput image-reader image-input-stream)
(.setOutput image-writer image-output-stream)
;; iio-image will contain the metadata
(let [iio-image (IIOImage. (.read image-reader 0) nil
(.getImageMetadata image-reader 0))
jpeg-params (doto (.getDefaultWriteParam image-writer)
(.setCompressionMode JPEGImageWriteParam/MODE_EXPLICIT)
;; 0.7 is the new compression level [0..1]
(.setCompressionQuality compressionQuality))]
(.write image-writer nil iio-image jpeg-params)))
(finally
(do (.dispose image-writer)
(.dispose image-reader))))))
(comment
(compress-jpg "path/to/inputFile.jpg" "path/to/outputFile.jpg" 0.7)
;; compress the input file so much, that it is obvious
(compress-jpg "src/sandbox/inputFile.jpg" "src/sandbox/outputFile.jpg" 0.01))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment