0

I've created and then saved a .bmp image file in R, and now I want to load the saved image back into R. (Just trust me that I have a semi-valid reason for doing this.) When I load the image file with bmp::read.bmp(), I get a warning message about invalid byte size information. Despite the warning, I can then plot the image, but the colors are messed up -- I think it has become grayscale rather than the original full color image.

Here's a simple example:

# fake data
n <- 1000
x <- rnorm(n)
y <- rnorm(n)

# draw a colorful scatter plot and save as a .bmp file
bmp("colorful plot.bmp", width = 300, height = 300)
par(mar = c(5, 5, 1, 1))
plot(x, y, cex = 5, pch = 16, col = hcl.colors(10))
dev.off()

# load the saved file back into R using the bmp package -- this raises a warning
my_bmp <- bmp::read.bmp("colorful plot.bmp", Verbose = TRUE)

# convert to raster, per the following post:
# https://stackoverflow.com/questions/16787894/need-help-converting-a-bmp-image-to-a-matrix-in-r
my_raster <- as.raster(my_bmp, max = 255)

# render the loaded bmp file
grid::grid.newpage()
grid::grid.raster(my_raster)

Here's the saved "colorful plot.bmp" file, in glorious full color: "colorful plot.bmp"

And here's a screenshot of my RStudio session, showing the image in crummy greyscale after it's been loaded back into R:

screenshot of bmp file after it has been re-loaded in R

Note that my code above to load and render a saved .bmp file works fine for a sample drawing I made in MS Paint, so the problem seems to be in the way bmp::read.bmp() reads a file created by grDevices::bmp().

Ideas on how to fix this?

In case it matters, I'm using R 4.3.1 (2023-06-16 ucrt) in RStudio 2023.06.0+421 on Windows 10 x64 (build 19044).

Dagremu
  • 325
  • 1
  • 7

0 Answers0