Just My Life & My Work

電腦圖學的人無不喜歡輸出的結果是一張圖,而不僅僅是文字!因此用C++來寫影像「Hello World」程式,是件基本且相當有趣的事情。

這裡使用PPM來實做彩色影像輸出,它是一個沒有壓縮過的影像格式,因此跟BMP一樣有著同樣大小的影像檔容量。

/**
	Theme: imageIO
	compiler: Dev C++ 4.9.9.2
	Date: 100/05/20
	Author: ShengWen
	Blog: https://cg2010studio.wordpress.com/
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct Pixel {
	unsigned char R, G, B;  // Blue, Green, Red
};

class ColorImage {
	Pixel *pPixel;
	int xRes, yRes;
public:
	ColorImage();
	~ColorImage();
	void init(int xSize, int ySize);
	void clear(Pixel background);
	Pixel readPixel(int x, int y);
	void writePixel(int x, int y, Pixel p);
	void outputPPM(char *filename);
};

ColorImage::ColorImage(){
	pPixel = 0;
}

ColorImage::~ColorImage(){
	if (pPixel) delete[] pPixel;
	pPixel = 0;
}

void ColorImage::init(int xSize, int ySize){
	Pixel p = {0,0,0};
	xRes = xSize;
	yRes = ySize;
	pPixel = new Pixel[xSize*ySize];
	clear(p);
}

void ColorImage::clear(Pixel background){
	int i;

	if (! pPixel) return;
	for (i=0; i<xRes*yRes; i++) pPixel[i] = background;
}

Pixel ColorImage::readPixel(int x, int y){
	assert(pPixel); // die if image not initialized
	return pPixel[x + y*yRes];
}

void ColorImage::writePixel(int x, int y, Pixel p){
	assert(pPixel); // die if image not initialized
	pPixel[x + y*yRes] = p;
}

void ColorImage::outputPPM(char *filename){
    FILE *outFile = fopen(filename, "wb");

	assert(outFile); // die if file can't be opened

	fprintf(outFile, "P6 %d %d 255\n", xRes, yRes);
	fwrite(pPixel, 1, 3*xRes*yRes, outFile );

	fclose(outFile);
}

// A test program that generates varying shades of reds.
int main(int argc, char* argv[]){
	ColorImage image;
	int x, y;
	Pixel p={0,0,0};

	image.init(256, 256);
	for (y=0; y<256; y++) {
		for (x=0; x<256; x++) {
			p.R = x;
			p.G = y;
			//p.B = y;
			image.writePixel(x, y, p);
		}
	}
	image.outputPPM("rainbow.ppm");
}

程式碼中main裡我初始一個256*256影像,然後將它的redgreen用兩個迴圈去填滿整張影像的資料結構,最後再將它輸出成檔案。檔案大小約略等於256*256*3=196608 bytes=196 KB

由於ppm影像格式已經退流行,所以必須藉由特殊看圖工具來開啟它,可以使用IrfanView免費看圖工具。

rainbow

ppm影像輸出結果,相當漂亮很像彩虹呢!

Comments on: "[C++] PPM影像檔輸出 (PPM image format output)" (1)

  1. 徐同學 的大頭貼

    您好 無意間看到你的文章
    我之前稍微研究一下ppm格式 發現有魔術數字P2 P3..等等差別
    請問P3地的建構方法有差別嗎?

隨意留個言吧:)~

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料

標籤雲