00001 #include "JPEG.h"
00002 #include "Demosaic.h"
00003
00004 #include <iostream>
00005
00006 using namespace std;
00007
00008 extern "C" {
00009 #include <jpeglib.h>
00010 }
00011
00012 namespace FCam {
00013 void saveJPEG_(Image im, string filename, int quality) {
00014 struct jpeg_compress_struct cinfo;
00015 struct jpeg_error_mgr jerr;
00016
00017 cout << "Saving jpeg" << endl;
00018
00019 FILE *f = fopen(filename.c_str(), "wb");
00020 if (!f) {
00021 cerr << "Could not open file: " << filename;
00022 return;
00023 }
00024
00025 cinfo.err = jpeg_std_error(&jerr);
00026 jpeg_create_compress(&cinfo);
00027 jpeg_stdio_dest(&cinfo, f);
00028
00029 cinfo.image_width = im.size.width;
00030 cinfo.image_height = im.size.height;
00031 cinfo.input_components = 3;
00032 if (im.type == RGB24) {
00033 cinfo.in_color_space = JCS_RGB;
00034 } else if (im.type == YUV24) {
00035 cinfo.in_color_space = JCS_YCbCr;
00036 }
00037
00038 jpeg_set_defaults(&cinfo);
00039 jpeg_set_quality(&cinfo, quality, TRUE);
00040
00041 jpeg_start_compress(&cinfo, TRUE);
00042
00043 JSAMPLE *row;
00044
00045 if (im.type == RGB24 || im.type == YUV24) {
00046 while (cinfo.next_scanline < cinfo.image_height) {
00047 row = im.data + cinfo.next_scanline * im.size.width * 3;
00048 jpeg_write_scanlines(&cinfo, &row, 1);
00049 }
00050 } else if (im.type == UYVY) {
00051 row = new JSAMPLE[cinfo.image_width*3];
00052 while (cinfo.next_scanline < cinfo.image_height) {
00053
00054 JSAMPLE *rowPtr = row;
00055 unsigned char *dataPtr = im.data + cinfo.next_scanline * im.size.width * 2;
00056 for (size_t i = 0; i < cinfo.image_width/2; i++) {
00057 rowPtr[0] = dataPtr[1];
00058 rowPtr[1] = dataPtr[0];
00059 rowPtr[2] = dataPtr[2];
00060 rowPtr[3] = dataPtr[3];
00061 rowPtr[4] = dataPtr[0];
00062 rowPtr[5] = dataPtr[2];
00063 rowPtr += 6;
00064 dataPtr += 4;
00065 }
00066 jpeg_write_scanlines(&cinfo, &row, 1);
00067 }
00068 delete[] row;
00069 }
00070
00071 jpeg_finish_compress(&cinfo);
00072 fclose(f);
00073 jpeg_destroy_compress(&cinfo);
00074
00075 cout << "Done saving jpeg" << endl;
00076 }
00077
00078 void saveJPEG(Frame::Ptr frame, string filename, int quality, Lens *lens, Flash *flash) {
00079 if (!frame || !frame->image.valid()) {
00080 cerr << "Cannot save an invalid image" << endl;
00081 return;
00082 }
00083
00084 Image im = frame->image;
00085
00086 switch (frame->image.type) {
00087 case RAW:
00088 im = demosaic(frame);
00089
00090 case RGB24: case YUV24: case UYVY:
00091 saveJPEG_(im, filename, quality);
00092 break;
00093 default:
00094 cerr << "Cannot save a jpeg from a frame in this format" << endl;
00095 }
00096 }
00097 };