`

Ruby版给图片加水印

阅读更多
ImageUtils.rb
#!/usr/local/bin/ruby

require 'logger'

module ImageUtils
	
	attr_accessor :watermarkText
	attr_accessor :watermarkResourceUri
	attr_accessor :watermarkFont
	attr_accessor :watermarkImage
	
	def initializeModule
		@watermarkText = "www.5iyya.com"
		@watermarkResourceUri = Dir.pwd
		@watermarkFont = "#{watermarkResourceUri}/fonts/simsun.ttc";
		@watermarkImage = "#{watermarkResourceUri}/watermark/logo_watermark.jpg"
		@logger = Logger.new(STDOUT)
	end

	#compress image according to given width and height
	def compress(origImages, width, height, suffix = '.summ.jpg')
		images = ImageList.new(origImages)
		images.each do |image|
			begin 
				anImage = image.scale(width, height)
				anImage.write(buildFileName(image.filename, suffix))
				
				rescue Exception => err
					puts "Compress failed due to : #{err}"
				ensure
					image.destroy! if !image.destroyed?
			end
		end
		return images
	end

	#rename the image name
	def renameImage(oriName, destName, keepOld = false, overwrite = true)
		fileSize = File.size(destName)
		if File.exist?(destName) && (fileSize == 0 && overwrite) then
			puts "File will be deleted since the size is zero and we will overwrite it."
			File.unlink(destName) 
		end
		if !File.exists?(destName) || fileSize == 0 then
			if keepOld then
				File.link(oriName, destName)
			else
				File.rename(oriName, destName)
			end
			File.utime(0, Time.now, destName) 
		end
	end

	#add watermark text to iamge
	def addWatermarkText(origImage, destImage=origImage, watermarkText=@watermarkText, watermarkFont=@watermarkFont)  
		images = ImageList.new(origImage)
		images.each do |image|
			begin 
				watermark = Draw.new  
			    watermark.annotate(image, 0, 0, 5, 5, watermarkText) do  #可设字的位置   
			      self.gravity = SouthEastGravity   
			      self.font = watermarkFont  
				  #这地方必须使用中文字库,才能打中文到图片上。在windows中c:\windows\fonts\simsun.ttc拷到项目的public \images目录下就可以随着项目使用了。另外注意:笔者是使用utf-8字符集来编辑源文件的,如果你不是,请在程序中对汉字转换编码为utf-8
			      self.pointsize = 24  #字体大小   
			      self.font_weight = BoldWeight   
			      self.fill = 'red' #字的颜色   
				  #self.undercolor = 'red' #背景颜色
			      self.gravity = SouthEastGravity   
			      self.stroke = "none"  
			    end 
				image.write(destImage)
				
				rescue Exception => err
					puts "addWatermarkText failed due to : #{err}"
				ensure
					image.destroy! if !image.destroyed?
			end
		end
	end
	
	#add watermark image to iamge
	def addWatermarkImage(origImage, destImage=origImage)
        images = ImageList.new(origImage)
		images.each do |image|
			begin
				# Make a watermark from the word "RMagick"
				mark = Image.read(@watermarkImage).first
				
				if !image.columns.nil? then
					width = image.columns.to_i
					#puts "width=#{width}"
					if width >= 1600 then
						@logger.warn("Image width >= 1600, will be minified twice!!")
						2.times do
							image.minify!
						end
					elsif width >= 760 then
						@logger.warn("Image width >= 760, will be minified once.")
						image.minify!
					end
								
					# Composite the watermark in the lower right (southeast) corner.
					if width <= 200 then
						@logger.warn("Image width <= 200")
						image.magnify!
						image.composite!(mark, SouthEastGravity, 0, 0, CopyCompositeOp)
					else
						image.composite!(mark, SouthEastGravity, 5, 5, CopyCompositeOp)
					end
				else
					@logger.error("Cannot read image.columns")
				end
				image.write(destImage)
				
				rescue Exception => err
					puts "addWatermarkImage failed due to : #{err}"
				ensure
					image.destroy! if !image.destroyed?
			end
		end
	end
	
	private 
		def buildFileName(originalName, suffix = '.summ.jpg')
			#puts "#{originalName}:#{suffix}"
			return originalName + suffix
		end
		
end


ImageProcessor.rb
#! /usr/local/bin/ruby 

require "RMagick"
include Magick
require "ImageUtils"

class ImageProcessor
	include ImageUtils
	
	def initialize
		initializeModule
	end
	
	#rename all images for given dir recursively
	def renameImagesRecursively(dir, originalSuffix = '.summ.jpg', replaceSuffix = '.summ', keepOld = false, overwrite = true)
		puts "renameImagesRecursively, Root Dir: #{dir}, originalSuffix = #{originalSuffix}, replaceSuffix = #{replaceSuffix}"
		renameImages(dir, originalSuffix, replaceSuffix, keepOld)
		Dir.foreach(dir){|item|
			curDir = dir + "/" + item
			#filtering
			if File.ftype(curDir) == "directory" && item != ".."  && item != "." && !item.include?("CVS") && !item.include?(".svn") then
				renameImagesRecursively(curDir, originalSuffix, replaceSuffix, keepOld, overwrite)
			end
		}
	end
	
	#rename all images for given dir
	def renameImages(dir, originalSuffix = '.summ.jpg', replaceSuffix = '.summ', keepOld = false, overwrite = true)
		puts "renameImages, Dir: #{dir}, originalSuffix = #{originalSuffix}, replaceSuffix = #{replaceSuffix}"
		Dir.foreach(dir){|imageName|
			curItem = dir + "/" + imageName
			if imageName.include?(originalSuffix) && !imageName.include?(".summ#{originalSuffix}") then
				puts "Update Item: #{dir}/#{imageName}"
				destName = dir + "/" + imageName.chomp(originalSuffix) + replaceSuffix
				renameImage(curItem, destName, keepOld, overwrite)
			end
		}
	end
	
	#add watermark and compress all images in given dir
	def addWatermarksAndCompressImages(dir, largeSuffix = ".l.jpg", smallSuffix = ".s.jpg")
		puts "addWatermarksAndCompress, Dir: #{dir}"
		Dir.foreach(dir){|imageName|
			curImage = dir + "/" + imageName
			if curImage.include?(".jpg") && !curImage.include?("nopic.gif") && !curImage.include?(largeSuffix) && !curImage.include?(smallSuffix) then
				puts "Update Item: #{dir}/#{imageName}"
				begin 
					addWatermarkImage(curImage)
					compress(curImage, 210, 188, largeSuffix)
					compress(curImage, 80, 80, smallSuffix)
					
					rescue Exception => err
						puts "Exception : #{err}"
					ensure
				end
			end
		}
	end
	
	#rename all images for given dir recursively
	def addWatermarksAndCompressImagesRecursively(dir, largeSuffix = ".l.jpg", smallSuffix = ".s.jpg")
		puts "addWatermarksAndCompressImagesRecursively, ROOT Dir: #{dir}"
		addWatermarksAndCompressImages(dir, largeSuffix, smallSuffix)
		Dir.foreach(dir){|item|
			curDir = dir + "/" + item
			#filtering
			if File.ftype(curDir) == "directory" && item != ".."  && item != "." && !item.include?("CVS") && !item.include?(".svn") then
				addWatermarksAndCompressImagesRecursively(curDir, largeSuffix, smallSuffix)
			end
		}
	end
	
end


ImageProcessorTest.rb
#! /usr/local/bin/ruby 

require 'test/unit'
require 'ImageProcessor'

class ImageProcessorTest < Test::Unit::TestCase

	def setup
		@processor = ImageProcessor.new
		@processor.watermarkFont = "test/simsun.ttc"
		@processor.watermarkText = "www.5iyya.com"
		@processor.watermarkImage = "test/logo_watermark.jpg"
	end
	
	def teardown
		@processor = nil
	end
	
	def test_renameImage
		#ImageUtils.renameImage("Cheetah.summ1.jpg", "Cheetah.summ")
	end
	
	def test_compress
		processedImage = @processor.compress('test/Cheetah.jpg',160, 120, '.summ.jpg')
		assert_not_nil(processedImage, 'Process image failed.')
	end
	
	def test_renameImagesRecursively
		Dir.chdir("C:/workspace/aiyaa/alibaba/images/images")
		@processor.renameImagesRecursively(Dir.pwd, ".jpg.l.jpg", ".jpg", true, true);
	end
	
	def test_copyImagesRecursively
		
	end
	
	def test_renameImages
		#Dir.chdir("C:/workspace/aiyaa/alibaba/images/images/jdjy3d")
		#@processor.renameImages(Dir.pwd, '.jpg.l.jpg', '.jpg', true, true);
	end
	
	def test_addWatermarksAndCompressImages
		#@processor.addWatermarksAndCompressImages(Dir.pwd + "/images")
	end
	
	def test_addWatermarksAndCompressImagesRecursively
		#@processor.addWatermarksAndCompressImagesRecursively(Dir.pwd + "/images")
	end
	
	def test_addWatermarkText
	   @processor.addWatermarkText('test/67971251.jpg', 'test/watermark_text.jpg')
	end
	
	def test_addWatermarkImage
	   @processor.addWatermarkImage('test/67971251.jpg', 'test/watermark_image.jpg')
	end
end

分享到:
评论

相关推荐

    GraphicsMagick+im4java.pdf

    很多网站都会用到对图片的一些处理,包括图片的裁剪、给图片加水印、按比例缩放图片等操作,用ImageMagick实现这些功能,性能非常好,图片还不会失真. 本文档详细的介绍了 GraphicsMagick+im4java的搭建过程,对...

    优道图片版权保护控件

    功能齐全 附带有放大、缩小、旋转、水印、颜色定制等图片浏览器常用功能,支持通过JavaScript与网页进行交互; 各种语言支持 服务器端支持Windows及Linux的服务器,支持各种服务器端编程语言,例如asp,asp.net,php,...

    优道PDF文档版权保护控件

    功能齐全 附带有放大、缩小、旋转、水印、颜色定制等图片浏览器常用功能,支持通过JavaScript或VbScript与网页进行交互; 各种语言支持 服务器端支持Windows及Linux的服务器,支持各种服务器端编程语言,例如asp,...

    阿里云-对象存储服务OSS最佳实践.pdf

    此外,还可以利用OSS的图片处理服务进行图片缩略和加水印等操作。 **总结:** 阿里云对象存储服务OSS的最佳实践提供了快速构建移动应用数据直传服务的指南,包括安全的鉴权机制、高效的直传模式以及灵活的存储解决...

    Aspose安装原包.rar

    5. **图像处理**:Aspose不仅仅处理文本文件,还支持图像处理,包括裁剪、旋转、水印、压缩等操作。 6. **邮件操作**:Aspose.Mail API允许开发者处理电子邮件,包括发送、接收、解析邮件,管理附件,甚至操作SMTP...

    优道PDF控件 ASP代码示例

    控件支持PDF动态水印定义功能,能给您最强有力的文档阅读和数字版权保护功能支持。产品特点:文件小巧 控件大小不超过3M,客户端不需要再另外安装其它庞大的PDF阅读器;使用简单 通过属性的设置和方法的调用即可完成...

    PDFlib指南

    - **水印添加**:提供简单的API来添加文字或图像水印。 #### 六、PDFlib的第三方软件组件 PDFlib集成了多个第三方软件组件,这些组件为PDFlib提供了额外的功能,例如: - **ICClib**:用于色彩管理,确保PDF文档...

    podofo.cr:PoDoFo C ++库的水晶绑定

    5. **添加水印**:在PDF页面上添加自定义水印,增强文档保护。 6. **数字签名**:对PDF文档进行数字签名,确保其完整性和安全性。 7. **加密解密**:设置或解除PDF的访问密码,控制阅读和编辑权限。 为了使用`...

Global site tag (gtag.js) - Google Analytics