Change size and aspect ratio without distortion - r

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.

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))

Related

space images in PDF using R

I'm using R to generate PDFs that contain QR code images. The images have to be arranged in a 4x6 pattern like this mockup that i made in Word:
I've written a loader that i plan to write into a loop later on (i've got over 2000 images). However, i can't quite get the spacing right. This is my current result:
It's not a bad thing that the images are smaller, but the large margins on top and bottom and right are a problem. I've been trying to set par(mar = c(4,0,0,0) in the loop to see if the images would get a bottom margin, but that doesn't happen. Also, i think i need to use padding instead of margin, but i haven't found a parameter for padding.
Is there a way to do this? The code i've written so far:
# import libraries
library(qrcode)
library(imager)
# clear workspace
rm(list = ls())
filenames <- list.files(path = "./QR/2/")
im <- load.image(paste0("./QR/2/",filenames[1]))
im <- list()
for(i in 1:24){
im[[i]] <- load.image(paste0("./QR/2/",filenames[i]))
}
pdf("./QR/2/stickervellen/1.pdf", paper = "a4")
par(mfrow = c(6,4), mar=c(0,0,0,0))
for(i in 1:24){
par(mar = c(4,0,0,0))
plot(im[[i]], axes = F)
}
dev.off()
the images i'm using can be found here: https://easyupload.io/v4gmbf
You have to specify the size of your graphics region with width and height. If you don't do that, default values (7 inch) are used and for an A4 paper which has a height of 11.7 inch you won't get full coverage.
pdf("./QR/2/stickervellen/1.pdf", paper="a4", width=8.3, height=11.7)
par(mfrow=c(6, 4), mar=rep(0, 4))
for(i in 1:24){
plot(im[[i]], axes=F)
box()
}
dev.off()
Please note that I added box() in your code so that the extent of the individual plots and the margins around them are visible.
In ?pdf you may also find that if you specify the paper argument
if either width or height is less than 0.1 or too large to give a total margin of 0.5 inch, it is reset to the corresponding paper dimension minus 0.5.
That's why there will always be a small margin around the whole page when you specify paper. If you don't want that margin, just leave out paper="a4" and you will get this:

Control how much space legend.only takes from a raster plot in r

I am trying to simply plot a raster map and a legend barr, but i cannot seem to get it at the right distance from the raster. Is either over it or too far. Also, despite i indicate a fixed width and height to the SVG printing function, the final size does not look similar. Would it be a way to control the exact position of the legend barr when plotting legend.only=T? By the way, stack overflow does not allow me to upload an SVG image, so i am uploading a screen capture that looks similar.
here is how i see it in R
Here is how i get it from the file generated
Here is the script used to generate that image, region and range are polygons, and hill and tmax are rasters. The plotting in R works fine-I just want to know how avoid the changes in the image from the R window to the file. There seems to be something in the exporting function that is creating a high white space between the map and the barr, and it express only when exporting the graph.
svg(paste("/Users/",spp[i],"filename", ".svg",sep=""),
bg="transparent", width = 5,height=5)
plot(region)
plot(hill,col=grey(0:100/100), add=T, legend=F)
plot(range,add=T, border="turquoise")
plot(Tmaxc>tmaxsp,col=heat.colors(100),add=T,legend=F)
plot(Tmaxc>tmaxsp,col=heat.colors(100),legend.only=TRUE, horizontal = TRUE,
legend.args = list(text='Warming tolerance\u00B0C', side = 1, line = 2))
dev.off()

Trying to save a graph in R, but the file is too big. Trying to shrink it

I need to save a graph to a word document in order to submit it to a medical journal. When I paste my graph into Word, the resolution is not great and it says it's scales to 22% of the original size. When I save it using an R code, the resolution is great. However, it appears that the image is quite big when I save it. If I change the scale to 100% of the original size in word, it is way too big for the document (but is clear).
I am using the following code to save it:
jpeg("filename.jpg", units="in", width=7, height=7, res=300)
CODE FOR PLOT
dev.off()
The journal requires at least 300dpi. The issue is likely that 7x7 is just too big because when I scale it down and insert it into word, it is very clear. However, I can't scale it down to anything lower than 7x7 because it will cut off parts of my plot.
How do I fix this situation? I would like to scale down the plot so it's a smaller size, without losing any resolution and cutting off any part of the graph.
I would submit the graph as 300dpi in the size you are happy with and the journal will be able to deal with it.
However, if you want to change height etc I would do the following:
tiff("test.tiff", width = 2700, height = 1600, units = 'px', res = 300)
plot(iris$Sepal.Length, iris$Petal.Length)
dev.off()
#OR different width height
tiff("test2.tiff", width = 700, height = 1000, units = 'px', res = 300)
plot(iris$Sepal.Length, iris$Petal.Length)
dev.off()

how to convert image to numerical (0-1) pixel matrix in R

i found the code to convert the image and got 480*288 numbers of data, because the pixel of the image is that. however, the matrix i want is just much less number matrix like: 19*12 or something. so how can i do that in the R? thanks a lot!.
library("EBImage")
img <- readImage("sample.jpg")
img <- channel(img, "grey")
write.csv(t(img), "sample.csv", row.names=FALSE)
In order to reduce the size of the resulting matrix you need to scale the image with resize before saving it to a .csv file, see my answer to Resizing image in R.

ggplot2 change in aspect while changing format

I recently tried to reproduce the Crime in Downtown Houston, Texas made by David Kahle, in order to reproduce it for another analysis later on.
Everything works well, and I can generate map as I want... However, there is an issue I cannot explain.
When I try to save the file at a larger format (let's say, 4500x1546 instead of the normal 1266x435), the size of the points, axis, title, legend etc. do not automatically adjust : they become way too small.
To illustrate this:
First image= 1200x435 (normal format), second image= 4500x1546 (adjusted format),
I observe the same effect with a geom_density plot..
I guess the solution is really trivial, but I didn't find it...
If you want to create a higher resolution png there are two approaches:
Increase the size in e.g. inches of the plot
Increase the dpi, the number of pixels per inch
You chose the second solution, this makes all the elements smaller, which is expected behavior. If you want to increase the resolution without changing the elements, increase the dpi. This can easily be done using ggsave:
g = ggplot(...)
# low res png
ggsave("lowres.png", width = 6, height = 6, dpi = 50)
# high res png
ggsave("hires.png", width = 6, height = 6, dpi = 600)
In this way there is no need to work with base_size.

Resources