Quick Tip : Compressing an image file on server using Scala

Here 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
    val param = writer.getDefaultWriteParam
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) // Setting Compression Mode
    // Specifying The Image Quality , We Can Choose The Quality Required
    writer.write(null, new IIOImage(image, null, null), param)
    // Closing The Input and Output Streams
    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

About Neelkanth Sachdeva

Project Manager @ eCIFM Solutions Inc. Previous : Senior Software Engineer @ Evernym Inc. Previous : Software Consultant @ Knoldus Software LLP Software Consultant @ Inphina Technologies
This entry was posted in Web. Bookmark the permalink.

3 Responses to Quick Tip : Compressing an image file on server using Scala

  1. dwinrick says:

    Thanks for this!
    Also – looks like the filename argument is not needed.

  2. dwinrick says:

    Thanks for this!
    Also, it looks like the filename argument isn’t needed.

  3. Pingback: Camera project update: less bandwidth consumption! | winrickLabs | Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s