开发者

RMagick's resample method resize the image, not resample it (the DPI resolution does not change)

I'm using RMagick’s resample method to change the DPI resolution of an image I have (from 300x300 to 72x72.

The code I use it this:

original_image = Magick::Image.read("my300x300file.jpg") { self.density = "72.0x72.0" }
original_image.each do |image|
   image = image.resample(72.0, 72.0)
   image.density = "72x72"
   image.write("my72x72file.jpg") { self.quality = 50 }
end

After executing the code, the my72x72file.jpg dimensions have been reduced, but its DPI resolution is still at 300 (which means the file size has not开发者_JAVA技巧 been reduced by much; in fact, even if I set the self.quality to 0, the file size pratically does not change).


Try image = image.resize_to_fit!(72.0, 72.0)
instead of image = image.resample(72.0, 72.0)

resize_to_fit changes the dimension of the image whereas resample changes the resolution (dpi) of the image. Normally the resolution is 96 dpi or 72 dpi. I have not seen an image with 300 dpi. Please give that a try.


Changing the resolution of your file doesn't (and shouldn't) change the file size. The resolution is the number of dots per inch, while file size is determined (after controlling for everything else like file size, compression, etc.) by the number of actual pixels, regardless of how many inches they are consuming.

If you want to change the resolution of your image (i.e. what Photoshop, GIMP, etc. say it is), the only thing I've found that works is creating a new image with the proper resolution, then compositing your original onto it. This seems counterproductive, but it's the only way I could get it to work at all.

Example code:

image = Magick::Image.read("my300x300file.jpg").first
dpi_image = Magick::Image.new(image.columns, image.rows) {
    self.density = "72x72"
    self.background_color = "none"
}
image = dpi_image.composite(image, Magick::CenterGravity, Magick::OverCompositeOp)


Old question but I ran into a similar problem and, apparently, this is still an issue. Changing the density on an image does not solve the problem, unless the units are also specified (default is UndefinedResolution, unlike what stated in the docs, here). Setting the units before setting the density worked for me (the other way around did not). In the above case, it should be something like:

original_image = Magick::Image.read("my300x300file.jpg") { self.density = "72.0x72.0" }
original_image.each do |image|
    image = image.resample(72.0, 72.0)
    image.units = Magick::PixelsPerInchResolution
    image.density = "72x72"
    image.write("my72x72file.jpg") { self.quality = 50 }
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜