我一直在为c ++寻找JPG保存库很长时间,但我似乎无法使用任何东西。现在我正在尝试使用LibGD:
我做错了什么?它似乎工作,但节省崩溃。代码:
...
#pragma comment(lib, "bgd.lib")
#include <gd/gd.h>
...
void save_test(){
gdImagePtr im;
FILE *jpegout;
int black;
int white;
im = gdImageCreateTrueColor(64, 64);
black = gdImageColorAllocate(im, 0, 0, 0);
white = gdImageColorAllocate(im, 255, 255, 255);
gdImageLine(im, 0, 0, 63, 63, white);
if(jpegout = fopen("test.jpg", "wb")){
if(im){
gdImageJpeg(im, jpegout, -1); // crash here!
}
fclose(jpegout);
}
gdImageDestroy(im);
}
我从http://www.libgd.org/releases/gd-latest-win32.zip
下载了这个库我将library / include / bgd.dll文件放在正确的目录中等。
修改:下面的答案包含修复我的问题的代码:
int size;
char* data = (char*)gdImagePngPtr(im, &size);
fwrite(data, sizeof(char), size, out);
gdFree(data);
答案 0 :(得分:2)
检查im
和jpegout
,然后再尝试使用它们以确保它们都已分配。
[编辑]最好从测试中分配文件句柄,以确定其有效性。你试过the libgd example吗?
[Edit2]我下载了相同的源码等,在VS2008中设置了一个项目并得到了完全相同的问题。你可以尝试this suggestion ..
关于GD的一个重要的事情是确保它是与主项目相同的CRT构建的,因为它使用诸如FILE之类的结构,如果你用另一个版本构建的可执行文件调用用一个版本的编译器构建的GD DLL,你将遇到内存访问违规。
那里有一个代码片段可以修复我机器上的崩溃:
/* Bring in gd library functions */
#include "gd.h"
/* Bring in standard I/O so we can output the PNG to a file */
#include <stdio.h>
int main() {
/* Declare the image */
gdImagePtr im;
/* Declare output files */
FILE *pngout, *jpegout;
/* Declare color indexes */
int black;
int white;
/* Allocate the image: 64 pixels across by 64 pixels tall */
im = gdImageCreate(64, 64);
/* Allocate the color black (red, green and blue all minimum).
Since this is the first color in a new image, it will
be the background color. */
black = gdImageColorAllocate(im, 0, 0, 0);
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);
/* Draw a line from the upper left to the lower right,
using white color index. */
gdImageLine(im, 0, 0, 63, 63, white);
/* Open a file for writing. "wb" means "write binary", important
under MSDOS, harmless under Unix. */
errno_t result1 = fopen_s(&pngout, "C:\\Projects\\Experiments\\LibGD\\test.png", "wb");
/* Do the same for a JPEG-format file. */
errno_t result2 = fopen_s(&jpegout, "C:\\Projects\\Experiments\\LibGD\\test.jpg", "wb+");
/* Output the image to the disk file in PNG format. */
int size;
char* data = (char*)gdImagePngPtr(im, &size);
fwrite(data, sizeof(char), size, pngout);
gdFree(data);
data = (char*)gdImageJpegPtr(im, &size, -1);
fwrite(data, sizeof(char), size, jpegout);
gdFree(data);
/* Close the files. */
fclose(pngout);
fclose(jpegout);
/* Destroy the image in memory. */
gdImageDestroy(im);
}