Created
July 18, 2021 00:09
-
-
Save duanebester/7bc9e81d4c5255b9adcf8bb0a6b57142 to your computer and use it in GitHub Desktop.
Image Processing with Cats and Scrimage - Scala 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
libraryDependencies += "commons-io" % "commons-io" % "2.10.0", | |
libraryDependencies += "com.sksamuel.scrimage" % "scrimage-core" % "4.0.20", | |
libraryDependencies += ("com.sksamuel.scrimage" %% "scrimage-scala" % "4.0.20").cross(CrossVersion.for3Use2_13), | |
*/ | |
import cats.effect.{ExitCode, IO, IOApp} | |
import com.sksamuel.scrimage.ImmutableImage | |
import com.sksamuel.scrimage.nio.PngWriter | |
import java.io.File | |
import java.net.URL | |
import org.apache.commons.io.FilenameUtils | |
import scala.jdk.CollectionConverters.* | |
enum SIZES(val pixels: Int): | |
case THUMBNAIL extends SIZES(160) | |
case MEDIUM extends SIZES(720) | |
case LARGE extends SIZES(1440) | |
object ImageTransformer extends IOApp: | |
def transformImages(image: ImmutableImage) = IO { | |
SIZES.values.toList.filter(_.pixels <= image.width).map { size => | |
image.scaleToWidth(size.pixels) | |
} :+ image | |
} | |
def saveImages(fileName: String, images: List[ImmutableImage]) = IO { | |
images.foreach { image => | |
image.output( | |
PngWriter.MaxCompression, | |
new File( | |
s"/Users/username/Downloads/$fileName-${image.width}.png" | |
) | |
) | |
} | |
} | |
def processImage(link: String): IO[ExitCode] = | |
for { | |
url <- IO(new URL(link)) | |
fileName <- IO(FilenameUtils.getName(url.getPath())) | |
inputStream <- IO(url.openConnection.getInputStream) | |
image <- IO(ImmutableImage.loader().fromStream(inputStream)) | |
tags <- IO(image.getMetadata.tags.toList) | |
scaled <- transformImages(image) | |
_ <- saveImages(fileName, scaled) | |
} yield ExitCode.Success | |
def run(args: List[String]) = processImage( | |
"https://some.url.com/products/8675309_0.jpg" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment