Added: trunk/image_voodoo/lib/image_voodoo.rb (0 => 888)
--- trunk/image_voodoo/lib/image_voodoo.rb (rev 0)
+++ trunk/image_voodoo/lib/image_voodoo.rb 2008-02-07 03:54:49 UTC (rev 888)
@@ -0,0 +1,75 @@
+#
+class ImageVoodoo
+ include Java
+ import java.awt.Image
+ import java.awt.RenderingHints
+ import java.awt.geom.AffineTransform
+ import java.awt.image.BufferedImage
+ import javax.imageio.ImageIO
+
+ def initialize(src)
+ @src = ""
+ end
+
+ def cropped_thumbnail(size)
+ l, t, r, b, half = 0, 0, width, height, (width - height).abs / 2
+ l, r = half, half + height if width > height
+ t, b = half, half + width if height > width
+
+ with_crop(l, t, r, b) { |img| img.thumbnail(size) { |thumb| yield thumb } }
+ end
+
+ def height
+ @src.height
+ end
+
+ def width
+ @src.width
+ end
+
+ def resize(width, height)
+ ge = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment
+ gc = ge.getDefaultScreenDevice.getDefaultConfiguration
+ transparency = @src.color_model.transparency
+ target = gc.create_compatible_image width, height, transparency
+ graphics = target.graphics
+ graphics.set_rendering_hint RenderingHints::KEY_INTERPOLATION, RenderingHints::VALUE_INTERPOLATION_BICUBIC
+ transform = AffineTransform.get_scale_instance width.to_f/@src.width, height.to_f/@src.height
+ graphics.draw_rendered_image @src, transform
+ graphics.dispose
+
+ yield ImageVoodoo.new(target)
+ end
+
+ def save(file)
+ return false if file !~ /\.(.*)$/
+
+ out = java.io.FileOutputStream.new file
+ ImageIO.write(@src, $1, out)
+ out.close
+ true
+ end
+
+ def thumbnail(size)
+ scale = size.to_f / (width > height ? width : height)
+ resize((width * scale).to_i, (height * scale).to_i) {|image| yield image }
+ end
+
+ def with_crop(left, top, right, bottom)
+ yield ImageVoodoo.new(@src.get_subimage(left, top, right - left, bottom - top))
+ end
+
+ def self.with_image(file)
+ yield ImageVoodoo.new(ImageIO.read(java.io.File.new(file)))
+ end
+end
+
+#ImageVoodoo.with_image(ARGV[0]) do |img|
+# img.cropped_thumbnail(100) { |img2| img2.save "CTH.jpg" }
+# img.with_crop(100, 200, 400, 600) { |img2| img2.save "CR.jpg" }
+# img.thumbnail(50) { |img2| img2.save "TH.jpg" }
+# img.resize(100, 150) do |img2|
+# img2.save "HEH.jpg"
+# img2.save "HEH.png"
+# end
+#end