Domanda

I'm trying to wrap my head around futures, and have a little sample of scaling a directory of images going...

Can some explain to me how this should work?

import com.sksamuel.scrimage._
import scala.concurrent._
import ExecutionContext.Implicits.global
import java.io._

object Test {

    def main(args: Array[String]) = {
        val dir = new File("/Users/bthibault/Downloads/ff_images/")
        dir.listFiles().foreach(file => AsyncImage(file).map( x => x.scale(0.5) ).onSuccess {
            case image => image.writer(Format.PNG).withMaxCompression.write(file)
        })
    }
}

I'm using the Scrimage package https://github.com/sksamuel/scrimage/ where he gives an example of the Async operation... here is the actual Async file:

https://github.com/sksamuel/scrimage/blob/master/core/src/main/scala/com/sksamuel/scrimage/AsyncImage.scala

Can somebody help me understand what I need to do to get this working? I was playing with the map() function ... my thought was I need to return a real 'image' onSuccess rather than an AsyncImage ....

È stato utile?

Soluzione

If you are trying to asynchronously resize all the images in the folder, and are asking for guidance on the correct syntax, then this will work:

object AsyncBatch extends App {

  val dir = new File(args(0)) 
  dir.listFiles.map(file =>
    AsyncImage(file)
      .flatMap(x => x.scale(0.5))
      .onSuccess {
      case image => image.writer(Format.PNG).write(file)
    })
}

Note: The withMaxCompression isn't supported on AsyncWriters. That's an oversight of the library.

Another way you can do this is with for comprehensions:

  val dir = new File(args(0)) 
  for ( file <- dir.listFiles;
        image <- AsyncImage(file);
        scaled <- image.scale(0.5) ) {
    scaled.writer(Format.PNG).write(file)
  }

Which I think is easier to read when you have lots of flatMaps and maps going on.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top