- #include <stdio.h>
- #include <stdlib.h>
- #include <jpeglib.h>
- typedef struct{
- unsigned char *image;
- int width;
- int height;
- } ImageData;
- typedef struct{
- unsigned char R;
- unsigned char G;
- unsigned char B;
- } Color;
- typedef struct{
- int x;
- int y;
- } Point;
- static int jpeg_make(FILE *fd, ImageData *buffer, int quality);
- static int draw_rectangle(ImageData *buffer, Point *UpLeft, Point *BottomRight, Color *color);
- int main(int argc, char * argv[])
- {
- FILE *fd = fopen("test1.jpg", "w");
- // malloc suitable buffer for image
- ImageData data;
- data.width = 400;
- data.height = 400;
- data.image = (unsigned char *)malloc(data.width * data.height * 3);
- // init buffer - white color
- int i=0;
- for(; i < data.width * data.height * 3; i++)
- data.image[i] = 255;
- // draw a rectangle
- Point A, B; Color color;
- A.x = 50; A.y = 50; B.x = 100; B.y = 100;
- color.R = 0; color.G = 0; color.B = 0;
- draw_rectangle(&data, &A, &B, &color);
- jpeg_make(fd, &data, 80);
- free(data.image);
- fclose(fd);
- return 0;
- }
- static int jpeg_make(FILE *fd, ImageData *buffer, int quality)
- {
- struct jpeg_compress_struct cinfo;
- struct jpeg_error_mgr jerr;
- cinfo.err = jpeg_std_error(&jerr);
- JSAMPROW row_ptr[1];
- jpeg_create_compress(&cinfo);
- jpeg_stdio_dest(&cinfo, fd);
- cinfo.image_width = buffer->width;
- cinfo.image_height = buffer->height;
- cinfo.input_components = 3;
- cinfo.in_color_space = JCS_RGB;
- jpeg_set_defaults(&cinfo);
- jpeg_set_quality(&cinfo, quality, TRUE);
- jpeg_start_compress(&cinfo, TRUE);
- while(cinfo.next_scanline < cinfo.image_height){
- row_ptr[0] = &buffer->image[cinfo.next_scanline * buffer->width * 3];
- jpeg_write_scanlines(&cinfo, row_ptr, 1);
- }
- jpeg_finish_compress(&cinfo);
- jpeg_destroy_compress(&cinfo);
- return 0;
- }
- static int draw_rectangle(ImageData *buffer, Point *UpLeft, Point *BottomRight, Color *color)
- {
- // out of range check! not done!!!
- int row_bytes = buffer->width * 3;
- int start = UpLeft->y * row_bytes;
- int end = BottomRight->y * row_bytes;
- int i;
- for(i=(start + UpLeft->x * 3); i<(start + BottomRight->x * 3); i+=3){
- buffer->image[i] = color->R;
- buffer->image[i+1] = color->G;
- buffer->image[i+2] = color->B;
- }
- for(i=(start + UpLeft->x * 3); i<(end + UpLeft->x * 3); i+=row_bytes){
- buffer->image[i] = color->R;
- buffer->image[i+1] = color->R;
- buffer->image[i+2] = color->R;
- }
- for(i=(start + BottomRight->x * 3); i<(end + BottomRight->x * 3); i+=row_bytes){
- buffer->image[i] = color->R;
- buffer->image[i+1] = color->R;
- buffer->image[i+2] = color->R;
- }
- for(i=(end + UpLeft->x * 3); i<(end + BottomRight->x * 3); i+=3){
- buffer->image[i] = color->R;
- buffer->image[i+1] = color->G;
- buffer->image[i+2] = color->B;
- }
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/291020136760.html
来源: http://www.codesnippet.cn/detail/291020136760.html