SDL_image を用いて画像ファイルを読み込むサンプルプログラム(Ubuntu 上)
SDL_image は, BMP, JPEG, PNG, PNM などの画像ファイルを扱う機能を持ったライブラリ. このページでは,SDL_image を用いて画像ファイルを読み込むプログラムの例を示す.
前準備
Ubuntu のシステム更新
Ubuntu で OS のシステム更新を行うときは, 端末で,次のコマンドを実行する.
sudo apt -y update
sudo apt -yV upgrade
sudo /sbin/shutdown -r now
SDL, SDL_image のインストール(ソースコードを使用)(Ubuntu 上)
sudo apt -y update
sudo apt -y install libsdl2-dev libsdl2-image-dev
プログラム例
画像ファイルはヘッダが付いていたり,しばしば圧縮されている.画像ファイルの種類もいろいろある. SDL_image を使うと,こうしたことを気にしなくて済む.
次の仮定を置く
- RGBのカラー画像
- 1画素の R, G, B 成分は1バイトであること.
- 画像データは隙間無くならんでいること.
- R, G, B の順に並んでいることを仮定している.
/* SDL を用いた画像読み込みファイルプログラム */
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include "SDL.h"
#include "SDL_image.h"
int main(int argc, char *argv[])
{
SDL_Surface *image;
int i, j;
int r, g, b;
/* Check command line usage */
if ( ! argv[1] ) {
fprintf(stderr, "Usage: %s <image_file>\n", argv[0]);
return(1);
}
/* Open the image file */
image = IMG_Load(argv[1]);
if ( image == NULL ) {
fprintf(stderr, "Couldn't load %s: %s\n", argv[1], SDL_GetError());
}
for ( i = 0; i < image->h; i++ ) {
for ( j = 0; j < image->w; j++ ) {
// 1画素の R, G, B 成分は1バイトであること.画像データは隙間無くならんでいること.R, G, B の順に並んでいることを仮定している.
unsigned char* p = (unsigned char*)image->pixels;
int pixel_at = (i * (image->w) + j ) * image->format->BytesPerPixel;
r = p[pixel_at];
g = p[pixel_at + 1];
b = p[pixel_at + 2];
fprintf(stderr, "%d, %d = (%d, %d, %d)\n", i, j, r, g, b);
}
}
fprintf( stderr, "image->format->BytesPerPixel = %d", image->format->BytesPerPixel );
fprintf( stderr, "image->w = %d", image->w );
fprintf( stderr, "image->h = %d", image->h );
/* We're done! */
SDL_Quit();
return(0);
}
ビルド手順
view.cpp のところは実際のファイル名に読み替えてください.
g++ -I/usr/include/SDL -I/usr/include/png12 -o a.out view.cpp -lSDL_image -lSDL -lpthread -lm