rimage-processingmagick-r-package

Change size and aspect ratio without distortion


i'm searching for a way in R to make 400x400px images (.jpg/.png) out of a larger images of different size and aspect size without distorting it. The new image should have most of the content of the original one but can be cut off a bit on the left and right so that it becomes a square without distortion.

How far I got (with distortion):

library(magick)

pics <- list.files("./")

for(i in 1:length(pics)){

  a <- image_read((paste0("./", pics[i], sep="")))

  b<-image_resize(a, "300x300!")

  image_write(b, path = paste0("./", pics[i], sep=""), format = "jpg")
}  

Thanks in advance!

Dominik.


Solution

  • You can add these lines right before the resize line b<-image_resize(a, "300x300!") to crop a so it is square.

    newdim <- min(image_info(a)[c('width', 'height')])
    a <- image_crop(a, geometry = geometry_area(newdim, newdim))