HTMLify
image.c
Views: 1 | Author: abh
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <stdbool.h>
#include <stdlib.h>
#include "image.h"
Image *load_image(const char *image_path) {
GError *error = NULL;
GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(image_path, &error);
if (error)
g_print("error in loading image: \n\t domain: %c\n\t message: %s\n", error->domain, error->message);
if (!pixbuf)
return NULL;
Image *image = pixbuf_to_image(pixbuf);
return image;
}
bool save_image(Image *image, const char *image_path) {
GdkPixbuf *pixbuf = image_to_pixbuf(image);
// int l;
// for (l=0;image_path[l];l++);
// for (;image_path[l]!='.';l--);
// g_print("file extention: %s\n", &image_path[l]);
GError *error = NULL;
bool s = gdk_pixbuf_save(pixbuf, image_path, "png", &error, NULL);
if (error)
g_print("error in saving image: \n\t domain: %c\n\t message: %s\n", error->domain, error->message);
return s;
}
GdkPixbuf *image_to_pixbuf(Image *image) {
GdkPixbuf *pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, false, 8, image->width, image->height);
int rs = gdk_pixbuf_get_rowstride(pixbuf);
int nc = gdk_pixbuf_get_n_channels(pixbuf);
guchar *p, *ps = gdk_pixbuf_get_pixels(pixbuf);
Pixel *_p;
int x, y;
for (y=0; y<image->height; y++) {
for (x=0; x<image->width; x++) {
p = ps + y*rs + x*nc;
_p = image_get_pixel(image, x, y);
p[0] = _p->r;
p[1] = _p->g;
p[2] = _p->b;
}
}
return pixbuf;
}
Image *pixbuf_to_image(GdkPixbuf *pixbuf) {
Image *image = malloc(sizeof(Image));
int rs = gdk_pixbuf_get_rowstride(pixbuf);
int nc = gdk_pixbuf_get_n_channels(pixbuf);
int x, y;
guchar *p, *ps = gdk_pixbuf_get_pixels(pixbuf);
Pixel *px;
image->width = gdk_pixbuf_get_width(pixbuf);
image->height = gdk_pixbuf_get_height(pixbuf);
image->pixels = (Pixel*)malloc(sizeof(Pixel)*image->width*image->height);
for (y=0; y<image->height; y++) {
for (x=0; x<image->width; x++) {
p = ps + y*rs + x*nc;
px = image_get_pixel(image, x, y);
px->r = p[0];
px->g = p[1];
px->b = p[2];
}
}
return image;
}
Image *image_new(int width, int height) {
Image *image = malloc(sizeof(Image));
image->width = width;
image->height = height;
image->pixels = malloc(sizeof(Pixel)*width*height);
return image;
}
Pixel *image_get_pixel(const Image *image, int x, int y) {
if (!image || !image->pixels || x < 0 || x >= image->width || y < 0 || y >= image->height)
return pixel_new(0, 0, 0);
return &image->pixels[image->width * y + x];
}
void image_set_pixel(Image *image, int x, int y, const Pixel *pixel) {
image_set_pixel_values(image, x, y, pixel->r, pixel->g, pixel->b);
}
void image_set_pixel_values(Image *image, int x, int y, unsigned char r, unsigned char g, unsigned char b) {
Pixel *p = image_get_pixel(image, x, y);
p->r = r;
p->g = g;
p->b = b;
}
Pixel *pixel_new(unsigned char r, unsigned char g, unsigned char b) {
return &(Pixel){(unsigned char)r, (unsigned char)g, (unsigned char)b};
}