0
  def getListOfImageNames(dir: String): List[String] = {
    val names = new File(dir)
    names.listFiles.filter(_.isFile)
      .map(_.getName).toList
  }


  def getListOfImages(dir: String): List[String] = {
    val files = new File(dir)
    files.listFiles.filter(_.isFile)
      .filter(_.getName.endsWith(".png"))
      .filter(_.getName.endsWith(".jpg"))
      .map(_.getPath).toList
  }

I have a directory where I have different photos, small size, large size and I have already managed to write methods which: one of them only pulls out the names of the photos and the other the photos. How can I now combine them into a map, for example, then calculate their resolution using the method, if the photo is larger than, for example, 500x500, add a prefix to the name and save it in the X folder. Do you have any ideas? I'm not experienced in Scala, but I like the language very much.

1 Answers1

1

As I got you need to get map of image name to image path. You can achieve it like so:

def getImagesMap(dirPath: String): Map[String, String] = {
  val directory = new File(dirPath)
  directory.listFiles.collect{
    case file if file.isFile && 
         (file.getName.endsWith(".png") ||
         file.getName.endsWith(".jpg")) => 
      file.getName -> file.getPath
  }.toMap
}

here I use collect function. It's like combination of map and filter functions. Inside collect a pattern matching expression. If file matches pattern matching it will evaluate pair creation: file name to file path. Otherwise file just will be filtered. After I use toMap for conversion Array[(String, String)] to Map[String, String]. You can read more about collect here.

jwvh
  • 50,871
  • 7
  • 38
  • 64
Boris Azanov
  • 4,408
  • 1
  • 15
  • 28
  • Ok, it's looking nice, I will test it now – Szymon Dejewski Oct 18 '20 at 17:51
  • Works fine, could you show me how I can work with this Map? e.g. how i count all the pixels in every image? and output it? – Szymon Dejewski Oct 18 '20 at 18:07
  • @SzymonDejewski you can `filter` Map by width and length of image, using `BufferedImage` class and `getWidth` and `getHeight` methods: https://stackoverflow.com/questions/672916/how-to-get-image-height-and-width-using-java – Boris Azanov Oct 18 '20 at 20:24