在生成图片的缩略图时,由于获取的缩略图长宽比例与原图的比例不同时就会导致生成的缩略图变形,为了生成无压缩变形的缩略图,比较方便编程实现的方式是:使用Epeg库。该库能够为JPEG格式图片生成缩略图,如果需要为其他格式的图片生成缩略图,那暂时只有先转换成JPEG图片的格式。
说多了,一切都是浮云,直接上代码:epeg缩略图生成方式:
char *epeg_trim_and_scale(const char *pszSrcFile,
size_t thumb_height,
size_t thumb_width,
int *pixels_size)
{
Epeg_Image *im;
unsigned char *thumb_pic=NULL;
unsigned char *mem_trim_out = NULL;
int trim_size = 0;
*pixels_size = 0;
im = epeg_file_open(pszSrcFile);
do{
if(!im){
break;
}
int w, h;
int x,y;
int im_w, im_h;
int ret;
int n = 0;
epeg_size_get(im, &w, &h);
if (thumb_width < 0) {
// This means we want %thumb_width of w
thumb_width = w * (-thumb_width) / 100;
}
if (thumb_height < 0) {
// This means we want %thumb_height of h
thumb_height = h * (-thumb_height) / 100;
}
im_w = w;
im_h = h;
x = 0;
y = 0;
if (im_w * thumb_height > im_h * thumb_width) {
x = (im_w - thumb_width * im_h / thumb_height) / 2;
} else {
y = (im_h - im_w * thumb_height / thumb_width) / 2;
}
w = x > 0 ? im_w - x * 2 : im_w;
h = y > 0 ? im_h - y * 2 : im_h;
//trim
if(x || y){
epeg_decode_bounds_set(im, x, y, w, h);
epeg_quality_set(im, 80);
epeg_memory_output_set(im,&mem_trim_out,&trim_size);
epeg_trim(im);
epeg_close(im);
//conitnue to scale
im = epeg_memory_open(mem_trim_out,trim_size);
if(!im){
break;
}
}
epeg_decode_size_set(im, thumb_width, thumb_height);
epeg_quality_set(im, 80);
epeg_thumbnail_comments_enable (im, 1);
epeg_memory_output_set(im, &thumb_pic, &n);//set the results
ret = epeg_encode(im);
OS_LOG(LOG_MODE_INTRANET_TRAN, LOGLV_DEBUG,"epeg_trim_and_scale return %d", ret);
if(ret == 0){
*pixels_size = n;
}
epeg_close(im);
}while(0);
if(mem_trim_out) {
free(mem_trim_out);
}
return (char*)thumb_pic;
}