September 29, 2012 Web3 Comments on Quick Tip : Compressing an image file on server using Scala1 min read Table of contents Share the Knol: Related Reading Time: < 1 minuteHere is the simple approach for compressing an image file on server using Scala. import java.io.FileInputStream import javax.imageio.ImageIO import java.io.File import java.io.FileOutputStream import javax.imageio.ImageWriter import java.awt.image.BufferedImage import javax.imageio.ImageWriteParam import javax.imageio.stream.ImageOutputStream import java.io.OutputStream import java.io.InputStream import javax.imageio.IIOImage import java.util.Iterator import java.io.ByteArrayOutputStream import java.io.ByteArrayInputStream object CompressFile extends App { val imageFile = new File("/home/neelkanth/Desktop/image1.JPG") def compressImage(file: File, filename: String, qualityOfOutPutImage: Float): InputStream = { val inputStream = new FileInputStream(file) // Creating An In Memory Output Stream val outPutStream = new ByteArrayOutputStream val image = ImageIO.read(inputStream) // BufferedImage val writers = ImageIO.getImageWritersByFormatName("jpg") val writer = writers.next val imageOutputStream = ImageIO.createImageOutputStream(outPutStream) // Image Output Stream writer.setOutput(imageOutputStream) val param = writer.getDefaultWriteParam param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) // Setting Compression Mode // Specifying The Image Quality , We Can Choose The Quality Required param.setCompressionQuality(qualityOfOutPutImage) writer.write(null, new IIOImage(image, null, null), param) // Closing The Input and Output Streams inputStream.close outPutStream.close imageOutputStream.close writer.dispose // Disposing writer // Creating The InputStream From ByteArrayInputStream val fileInputStream: InputStream = new ByteArrayInputStream(outPutStream.toByteArray) fileInputStream // Returned The Compressed Image Input Stream } // Calling The Function compressImage(imageFile,imageFile.getName,0.1f) } Share the Knol:Click to share on LinkedIn (Opens in new window)Click to share on Twitter (Opens in new window)Click to share on Telegram (Opens in new window)Click to share on Facebook (Opens in new window) Related
Thanks for this!
Also – looks like the filename argument is not needed.
Thanks for this!
Also, it looks like the filename argument isn’t needed.