Ruby 讀取png圖片的信息

學習ruby,嘗試用ruby讀取png的基本信息。

網上找到的開源的庫chunky_png, 下載地址: https://github.com/wvanbergen/chunky_png。

chunky_png 是一個很強大的庫,可以修改png圖片的數據。


本小例子只是讀取一些基本的信息。

require "chunky_png"

class PngImageInfo
	def initialize()
		@image = nil;
	end
	# 加載png圖片
	def setImagePath(path)
		@image = ChunkyPNG::Image.from_file(path);
	end

	#獲取png數據
	def getImage
		@image;
	end

	#獲取圖片的大小
	def getImageSize
		{"width"=>@image.dimension.width, "height"=>@image.dimension.height};
	end

	#獲取圖片的在x,y出的像素值
	def getImagePixelAtPoint(x, y)
		@image.get_pixel(x, y);
	end

	def getImageColorRAt(x, y)
		@image.get_pixel(x, y) >> 24
	end

	def getImageColorGAt(x, y)
		@image.get_pixel(x, y) >> 16 & 0xFF
	end

	def getImageColorBAt(x, y)
		@image.get_pixel(x, y) >> 8 & 0xFF
	end

	#獲取圖片在x,y出的alpha值
	def getImageColorAlphaAt(x, y)
		@image.get_pixel(x, y) & 0xFF
	end
end

texture = PngImageInfo.new();
texture.setImagePath("soldier.png");
puts texture.getImageSize;
puts texture.getImagePixelAtPoint(287,133);
puts texture.getImageColorRAt(287,133);
puts texture.getImageColorGAt(287,133);
puts texture.getImageColorBAt(287,133);
puts texture.getImageColorAlphaAt(287,133);
puts texture.getImageColorAlphaAt(374,250);




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章