1

I would like to ask if is correct way of using it when I want to save file in memory from writer and convert it to BufferedImage or should i write it to outputstream and convert it to BufferedImage?

Link to documentation https://sksamuel.github.io/scrimage/io/

My code looks like this:

def getImage(url: URL, width: Int, height: Int): BufferedImage = {
    val writer = new PngWriter()
    val image = ImmutableImage.loader().fromStream(url.openStream()).fit(width, height)
    image.replaceTransparencyInPlace(Color.white)
    ImageIO.read(image.forWriter(writer).stream())
  }
Marius
  • 151
  • 5

1 Answers1

1

If you want to read a URL and return a java BufferedImage then you should a) close the stream once complete and b) there is no need to reparse the image, just return the awt image that Scrimage uses under the hood.

If you are using Scala 2.13 then you can use Using to handle resources.

For example:

def getImage(url: URL, width: Int, height: Int): BufferedImage = {
  val writer = new PngWriter()
  Using(url.openStream()) { stream =>
    val image = ImmutableImage.loader().fromStream(stream).fit(width, height)
    image.replaceTransparencyInPlace(Color.white).awt()
  }
}
sksamuel
  • 16,154
  • 8
  • 60
  • 108