如何创建图像?

时间:2014-04-03 12:00:43

标签: c++ image

在C ++中如何在没有任何库的情况下创建具有跨平台支持的图像?

我在没有任何库的情况下这样做的原因是因为我需要速度。我希望有一个3字节整数的数组,并编辑数据像素像素。

在C ++中是否有图像数据类型?如果没有,我该如何模拟一个?

要明确:我想在不使用任何库的情况下处理数据。保存到PNG将使用库完成。

1 个答案:

答案 0 :(得分:1)

C ++或STL没有图像的标准概念。对于基本表示,您可以使用以下内容:

#include <stdlib.h>
#include <memory.h>


struct Color {
    unsigned char r;
    unsigned char g;
    unsigned char b;
};


class Image {
public:
    const int width;
    const int height;
    Color * const data;

    Image( int width, int height ) : width( width ), height( height ), data( (Color*) malloc( sizeof( Color) * width * height ) )
    {
        memset( (void*) data, 0, sizeof( Color) * width * height );
    }

    ~Image() {
        free( (void*) data );
    }

    void setpixel( int x, int y, Color c ) {
        data[ x + y * width ] = c;
    }

    Color getpixel( int x, int y ) const {
        return data[ x + y * width ];
    }
};



int main(int argc, const char * argv[])
{
    Image img( 320, 200 );
    img.setpixel( 10, 10, { 50, 255, 0 } );

    Color c = img.getpixel( 10, 10 );

    return 0;
}