关于 bmp 和 gif 文件的相互转换,急用

shipatrioc 2002-01-11 11:34:35
最近要写一个程序,就是把bmp转换为 gif,可我不知道它们的文件格式,那位大虾可以告诉我
...全文
348 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
snake1122 2002-01-18
  • 打赏
  • 举报
回复
我也在等!:)
Soft21 2002-01-13
  • 打赏
  • 举报
回复
大家好啊,好啊,我在等待大家的答案,呵呵!
wwwsq 2002-01-12
  • 打赏
  • 举报
回复
CXImage
- Davide Pizzolato (3 Jan 2002) [Updated]
CxImage is a C++ class to load, save, display, transform BMP,
JPEG, GIF, PNG, TIFF, MNG, and ICO images.
http://www.codeproject.com/bitmap/cximage.asp

很完善的一个处理图象的开发包,有源代码,已经升级到3.0。推荐!!

dgj 2002-01-12
  • 打赏
  • 举报
回复
去http://www.codeguru.com 看去,给我分!!!!!!!!!!
shipatrioc 2002-01-12
  • 打赏
  • 举报
回复
谢谢各位,我试一下
bzshow 2002-01-12
  • 打赏
  • 举报
回复
gif2bmp bmp2gif dither
hexgifc.zip [19K bytes] C source files.
hexgife.zip [66K bytes] Win32 executable files.
gif2bmp Convert Compuserve .gif to Microsoft Windows .bmp
bmp2gif Convert Microsoft Windows .bmp to Compuserve .gif
dither Floyd-Steinberg dither 24-bit Windows .bmp to 8- or 4-bit .bmp
For more information see description/options
bzshow 2002-01-12
  • 打赏
  • 举报
回复
把网址告诉你吧.

http://www.hexatron.com/soft/
bzshow 2002-01-12
  • 打赏
  • 举报
回复
bmp to gif

/* bmp2gif.c -- See end-of-file for (C) */
/* This was written for Microsoft 32-bit-integer compilers--it
* should compile with
* cl gif2bmp.c
* to produce the executable gif2bmp.exe
*
* The Microsoft oddities are:
* The funny include files -- they may be omitted on compilers
* that can not find them (stdio.h better be there, however)
* #pragma pack(1) -- This forces the BITMAPFILEHEADER structure
* to be the same length in memory as in files (otherwise, the structure
* is padded out to be a multiple of 8? bytes long
* Note that Microsoft uses all-caps for typedefs. Ugh.
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

typedef unsigned char byte;
typedef unsigned short WORD;
typedef unsigned long DWORD;

#pragma pack(1)
typedef struct tagRGBQUAD {
byte rgbBlue;
byte rgbGreen;
byte rgbRed;
byte rgbReserved;
} RGBQUAD;
typedef struct tagBITMAPFILEHEADER {
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} BITMAPFILEHEADER;
typedef BITMAPFILEHEADER *PBITMAPFILEHEADER;

typedef struct tagBITMAPINFOHEADER{
DWORD biSize;
DWORD biWidth;
DWORD biHeight;
WORD biPlanes;
WORD biBitCount;

DWORD biCompression;
DWORD biSizeImage;
DWORD biXPelsPerMeter;
DWORD biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} BITMAPINFOHEADER;

BITMAPFILEHEADER hdr;
BITMAPINFOHEADER bi;
long wib;
int yat;
unsigned char cmap[256*4]; /* Bytes of blue, green, red, reserved */
unsigned char omap[256*4]; /* Output colormap */
unsigned char *scanline;
unsigned char used[256];

FILE *fpin; /* Input file fp */
int c666= 0; /* Force output colormap to 666 colors */
int ncolors;

int fread_chk(char *cp, int n, int count, FILE *fp){
int c= fread(cp, n, count, fp);
if(c!=count){
perror("Read error:");
exit(1);
}
}
int fwrite_chk(char *cp, int n, int count, FILE *fp){
int c= fwrite(cp, n, count, fp);
if(c!=count){
perror("Write error:");
exit(1);
}
}
static int dib_wib(int bitcount, int wi){
switch (bitcount){
case 1: wi= (wi+31) >> 3; break;
case 4: wi= (wi+7) >> 1; break;
case 8: wi= wi+3; break;
case 24:wi= (wi*3)+3; break;
}
return wi & ~3;
}
void err(char *msg){
fprintf(stderr, "%s\n", msg);
exit(5);
}
void gulp(char *dibname){
int nbytes;
int v, y;

if((fpin= fopen (dibname, "rb"))==0){
perror(dibname);
exit(0);
}
fread_chk((char *)(&hdr),1,sizeof(hdr),fpin);
if(hdr.bfType!= 0x4d42)
err("Image not a .bmp");

fread_chk((char *)(&bi), 1, sizeof(bi), fpin);

wib= dib_wib((int)bi.biBitCount, (int)bi.biWidth);
bi.biSizeImage= bi.biHeight * wib;
if(bi.biBitCount != 8)
err("Only 8-bit .bmp images are permitted");
if(bi.biBitCount<=8){
v= (int)((hdr.bfOffBits - bi.biSize - sizeof(BITMAPFILEHEADER))/sizeof(RGBQUAD));
bi.biClrUsed= v;
if(v>0)
fread_chk(cmap, sizeof(RGBQUAD), v, fpin);
if(c666){
int k= 4*v;
while(--k>=0)
cmap[k]= 51*((cmap[k]+25)/51);
}
}
scanline= malloc((int)wib);
if(scanline==0)
err("Not enough room for the scanline");
fread_chk(scanline, 1, (int)wib, fpin);
yat= 0;
}
static int GetPixel(int x, int y){
y= (int)(bi.biHeight-1-y); /* bmp files are upside-down */
if(y!=yat){
if(y!=yat+1)
if(0!=fseek(fpin, (y-(yat+1))*wib, SEEK_CUR)){
perror("Seek on input file");
exit(1);
}
fread_chk(scanline, 1, (int)wib, fpin);
yat= y;
}
return used[scanline[x]];
}
int formoutputcmap(){
int ncolors= 0;
int x, y;
for(x= 0; x<256; x++)used[x]= 0;
for(y= 0; y<(int)bi.biHeight; y++){
if(y!=0)
fread_chk(scanline, 1, (int)wib, fpin);
for(x= 0; x<(int)bi.biWidth; x++)
used[scanline[x]]= 1;
}
/* Count the number of colors used */
for(x= 0; x<256; x++)ncolors += used[x];
if(ncolors<2)
ncolors= 2;
for(x= y= 0; x<256; x++)if(used[x]!=0){
used[x]= y/3;
omap[y++]= cmap[4*x+2];
omap[y++]= cmap[4*x+1];
omap[y++]= cmap[4*x];
}
fclose(fpin);
return ncolors;
}
int nearestcolor(int *rgb){
int k;
int pv= 0;
int n= 1 << ((int)bi.biBitCount);
long del[3], len, minlen= 3*256L*256L;
unsigned char *cp= cmap;

for(k= 0; k<n; k++, cp+= 4){
del[0]= cp[0]-rgb[2];
del[1]= cp[1]-rgb[1];
del[2]= cp[2]-rgb[0];
len= del[0]*del[0] + del[1]*del[1] + del[2]*del[2];
if(len<minlen){
minlen= len;
pv= k;
}
}
return pv;
}
char *note[]= {
"Usage: [-i] [-x # [# #]] [-b # [# #]] source.bmp dest.gif",
"Create a .gif file from a Windows .bmp file",
"Options:",
"-i Interlace [default not]",
"-x # Set pvalue # transparent (# # # for transparent rgb)",
"-b # Set pvalue # background [default 0]",
// "-p # Bits per pixel (override the number in the .bmp file)",
"-c X Add comment X (use quoted string argument)",
"-n Convert colors to nearest Netscape color [multiple of 51]",
0};
char *comment;
typedef int (* ifunptr)(int, int);
static void GIFEncode(FILE *fp, int GWidth, int GHeight,
int GInterlace, int Background, int Transparent,
int BitsPerPixel, unsigned char *cmap, ifunptr GetPixel );
void main(int ac, char **av){
int k;
int GWidth;
int GHeight;
FILE *fp;
int GInterlace= 0;
int Background;
int Transparent;
int BitsPerPixel= -1;

char *cp;
static int xpar[3]= {-1,-1,-1};
static int bg[3]= {0,-1,-1};
char *srcname= 0;
char *dstname= 0;

while(cp= *++av)if(*cp++=='-')switch(*cp++){
case 'n': c666= 1; break;
case 'c': comment= *++av; break;
// case 'p': BitsPerPixel= atoi(*++av);
// if(BitsPerPixel>8)
// BitsPerPixel= 8;
// break;
case 'i': GInterlace= 1; break;
case 'x': xpar[0]= atoi(*++av);
if(av[1][0]>='0' && av[1][0]<='9'){
xpar[1]= atoi(*++av);
xpar[2]= atoi(*++av);
} break;
case 'b': bg[0]= atoi(*++av);
if(av[1][0]>='0' && av[1][0]<='9'){
bg[1]= atoi(*++av);
bg[2]= atoi(*++av);
} break;
default:
erra: for(av= note; *av; ++av)
fprintf(stderr, "%s\n", *av);
exit(1);
}else if(srcname==0)
srcname= *av;
else if(dstname==0)
dstname= *av;
else
goto erra;
if(dstname==0)
goto erra;

/* Open the source bmp */
gulp(srcname);

/* Choose the output colors */
ncolors= formoutputcmap();
for(BitsPerPixel= 0; (1 << BitsPerPixel)<ncolors; BitsPerPixel++);
gulp(srcname);

/* Create the gif file */
fp= fopen(dstname, "wb");
if(fp==0){
perror(dstname);
exit(1);
}
/* Transfer some parameters */
GWidth= (int)bi.biWidth;
GHeight= (int)bi.biHeight;
Transparent= xpar[0];
if(xpar[1]>=0)
Transparent= used[nearestcolor(xpar)];
Background= bg[0];
if(bg[1]>=0)
Background= used[nearestcolor(bg)];

GIFEncode(fp, GWidth, GHeight,
GInterlace, Background, Transparent,
BitsPerPixel, omap, GetPixel);

printf("%d colors in %s\n", ncolors, srcname);
}
/*****************************************************************************
*
* GIFENCODE.C - GIF Image compression interface
*
* GIFEncode( FName, GHeight, GWidth, GInterlace, Background, Transparent,
* BitsPerPixel, Red, Green, Blue, GetPixel )
*
*****************************************************************************/
#define TRUE 1
#define FALSE 0

static int Width, Height;
static int curx, cury;
static long CountDown;
static int Pass = 0;
static int Interlace;
typedef int code_int;

#ifdef SIGNED_COMPARE_SLOW
typedef unsigned long int count_int;
typedef unsigned short int count_short;
#else /*SIGNED_COMPARE_SLOW*/
typedef long int count_int;
#endif /*SIGNED_COMPARE_SLOW*/

static void Putword ( int w, FILE* fp );
static void compress ( int init_bits, FILE* outfile, ifunptr ReadValue );
static void output ( code_int code );
static void cl_block ( void );
static void cl_hash ( count_int hsize );
static void writeerr ( void );
static void char_init ( void );
static void char_out ( int c );
static void flush_char ( void );


/*
* Bump the 'curx' and 'cury' to point to the next pixel
*/
static void BumpPixel() {
/* Bump the current X position */
++curx;

/*
* If we are at the end of a scan line, set curx back to the beginning
* If we are interlaced, bump the cury to the appropriate spot,
* otherwise, just increment it.
*/
if( curx == Width ) {
curx = 0;
if( !Interlace )
++cury;
else {
switch( Pass ) {
case 0:
cury += 8;
if( cury >= Height ) {
++Pass;
cury = 4;
} break;
case 1:
cury += 8;
if( cury >= Height ) {
++Pass;
cury = 2;
} break;
case 2:
cury += 4;
if( cury >= Height ) {
++Pass;
cury = 1;
} break;
case 3:
cury += 2;
break;
}
}
}
}

/*
* Return the next pixel from the image
*/
static int GIFNextPixel(ifunptr getpixel){
int r;

if( CountDown == 0 )
return EOF;
--CountDown;

r = ( * getpixel )( curx, cury );
BumpPixel();
return r;
}

/* public */
static void GIFEncode(FILE *fp, int GWidth, int GHeight,
int GInterlace, int Background, int Transparent,
int BitsPerPixel, unsigned char *omap, ifunptr GetPixel ){

int B;
int RWidth, RHeight;
int LeftOfs, TopOfs;
int Resolution;
int ColorMapSize;
int InitCodeSize;
int i;

Interlace = GInterlace;

ColorMapSize = 1 << BitsPerPixel;

RWidth = Width = GWidth;
RHeight = Height = GHeight;
LeftOfs = TopOfs = 0;

Resolution = BitsPerPixel;

/* Calculate number of bits we are expecting */
CountDown = (long)Width * (long)Height;

/* Indicate which pass we are on (if interlace) */
Pass = 0;

/* The initial code size */
if( BitsPerPixel <= 1 )
InitCodeSize = 2;
else
InitCodeSize = BitsPerPixel;

/* Set up the current x and y position */
curx = cury = 0;

/* Write the Magic header */
fwrite_chk( Transparent < 0 ? "GIF87a" : "GIF89a", 1, 6, fp );

/* Write out the screen width and height */
Putword( RWidth, fp );
Putword( RHeight, fp );

/* Indicate that there is a global colour map */
B = 0x80; /* Yes, there is a color map */

/* OR in the resolution */
B ¦= (Resolution - 1) << 5;

/* OR in the Bits per Pixel */
B ¦= (BitsPerPixel - 1);

/* Write it out */
fputc( B, fp );

/* Write out the Background colour */
fputc( Background, fp );

/* Byte of 0's (future expansion) */
fputc( 0, fp );

/* Write out the Global Colour Map */
for( i=0; i<ColorMapSize; ++i ) {
fputc( omap[0], fp ); // Red
fputc( omap[1], fp ); // Green
fputc( omap[2], fp ); // Blue
omap += 3;
}
/* Write out extension for transparent colour index, if necessary. */
if ( Transparent >= 0 ) {
fputc( '!', fp );
fputc( 0xf9, fp );
fputc( 4, fp );
fputc( 1, fp );
fputc( 0, fp );
fputc( 0, fp );
fputc( Transparent, fp );
fputc( 0, fp );
}
if (comment!=0 && *comment){
fputc( '!', fp);
fputc( 0xfe, fp);
fputc( strlen(comment), fp);
do
fputc( *comment, fp);
while(*comment++);
}
/* Write an Image separator */
fputc( ',', fp );

/* Write the Image header */
Putword( LeftOfs, fp );
Putword( TopOfs, fp );
Putword( Width, fp );
Putword( Height, fp );

/* Write out whether or not the image is interlaced */
if( Interlace )
fputc( 0x40, fp );
else
fputc( 0x00, fp );

/* Write out the initial code size */
if(EOF==fputc( InitCodeSize, fp )){
perror("Writing output");
exit(1);
}
/* Go and actually compress the data */
compress( InitCodeSize+1, fp, GetPixel );

/* Write out a Zero-length packet (to end the series) */
fputc( 0, fp );

/* Write the GIF file terminator */
fputc( ';', fp );

/* And close the file */
fclose( fp );
}

/* Write out a word to the GIF file */
static void Putword(int w, FILE *fp ){
fputc( w & 0xff, fp );
fputc( (w / 256) & 0xff, fp );
}
/***************************************************************************
*
* GIFCOMPR.C - GIF Image compression routines
*
* Lempel-Ziv compression based on 'compress'. GIF modifications by
* David Rowley (mgardi@watdcsu.waterloo.edu)
*
***************************************************************************/

/* General DEFINEs */

#define BITS 12
#define HSIZE 5003 /* 80% occupancy */

#ifdef NO_UCHAR
typedef char char_type;
#else /*NO_UCHAR*/
typedef unsigned char char_type;
#endif /*NO_UCHAR*/

/*
*
* GIF Image compression - modified 'compress'
*
* Based on: compress.c - File compression ala IEEE Computer, June 1984.
*
* By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
* Jim McKie (decvax!mcvax!jim)
* Steve Davies (decvax!vax135!petsd!peora!srd)
* Ken Turkowski (decvax!decwrl!turtlevax!ken)
* James A. Woods (decvax!ihnp4!ames!jaw)
* Joe Orost (decvax!vax135!petsd!joe)
*
*/
#include <ctype.h>

#define ARGVAL() (*++(*argv) ¦¦ (--argc && *++argv))

static int n_bits; /* number of bits/code */
static int maxbits = BITS; /* user settable max # bits/code */
static code_int maxcode; /* maximum code, given n_bits */
static code_int maxmaxcode = (code_int)1 << BITS; /* should NEVER generate this code */
#ifdef COMPATIBLE /* But wrong! */
# define MAXCODE(n_bits) ((code_int) 1 << (n_bits) - 1)
#else /*COMPATIBLE*/
# define MAXCODE(n_bits) (((code_int) 1 << (n_bits)) - 1)
#endif /*COMPATIBLE*/

static count_int htab [HSIZE];
static unsigned short codetab [HSIZE];
#define HashTabOf(i) htab[i]
#define CodeTabOf(i) codetab[i]

static code_int hsize = HSIZE; /* for dynamic table sizing */

/*
* To save much memory, we overlay the table used by compress() with those
* used by decompress(). The tab_prefix table is the same size and type
* as the codetab. The tab_suffix table needs 2**BITS characters. We
* get this from the beginning of htab. The output stack uses the rest
* of htab, and contains characters. There is plenty of room for any
* possible stack (stack used to be 8000 characters).
*/

#define tab_prefixof(i) CodeTabOf(i)
#define tab_suffixof(i) ((char_type*)(htab))[i]
#define de_stack ((char_type*)&tab_suffixof((code_int)1<<BITS))

static code_int free_ent = 0; /* first unused entry */

/*
* block compression parameters -- after all codes are used up,
* and compression rate changes, start over.
*/
static int clear_flg = 0;

static int offset;
static long int in_count = 1; /* length of input */
static long int out_count = 0; /* # of codes output (for debugging) */

/*
* compress stdin to stdout
*
* Algorithm: use open addressing double hashing (no chaining) on the
* prefix code / next character combination. We do a variant of Knuth's
* algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
* secondary probe. Here, the modular division first probe is gives way
* to a faster exclusive-or manipulation. Also do block compression with
* an adaptive reset, whereby the code table is cleared when the compression
* ratio decreases, but after the table fills. The variable-length output
* codes are re-sized at this point, and a special CLEAR code is generated
* for the decompressor. Late addition: construct the table according to
* file size for noticeable speed improvement on small files. Please direct
* questions about this implementation to ames!jaw.
*/

static int g_init_bits;
static FILE* g_outfile;

static int ClearCode;
static int EOFCode;

static void compress(int init_bits, FILE *outfile, ifunptr ReadValue ){
register long fcode;
register code_int i /* = 0 */;
register int c;
register code_int ent;
register code_int disp;
register code_int hsize_reg;
register int hshift;

/*
* Set up the globals: g_init_bits - initial number of bits
* g_outfile - pointer to output file
*/
g_init_bits = init_bits;
g_outfile = outfile;

/*
* Set up the necessary values
*/
offset = 0;
out_count = 0;
clear_flg = 0;
in_count = 1;
maxcode = MAXCODE(n_bits = g_init_bits);

ClearCode = (1 << (init_bits - 1));
EOFCode = ClearCode + 1;
free_ent = ClearCode + 2;

char_init();

ent = GIFNextPixel( ReadValue );

hshift = 0;
for ( fcode = (long) hsize; fcode < 65536L; fcode *= 2L )
++hshift;
hshift = 8 - hshift; /* set hash code range bound */

hsize_reg = hsize;
cl_hash( (count_int) hsize_reg); /* clear hash table */

output( (code_int)ClearCode );

#ifdef SIGNED_COMPARE_SLOW
while ( (c = GIFNextPixel( ReadValue )) != (unsigned) EOF ) {
#else /*SIGNED_COMPARE_SLOW*/
while ( (c = GIFNextPixel( ReadValue )) != EOF ) { /* } */
#endif /*SIGNED_COMPARE_SLOW*/

++in_count;

fcode = (long) (((long) c << maxbits) + ent);
i = (((code_int)c << hshift) ^ ent); /* xor hashing */

if ( HashTabOf (i) == fcode ) {
ent = CodeTabOf (i);
continue;
} else if ( (long)HashTabOf (i) < 0 ) /* empty slot */
goto nomatch;
disp = hsize_reg - i; /* secondary hash (after G. Knott) */
if ( i == 0 )
disp = 1;
probe:
if ( (i -= disp) < 0 )
i += hsize_reg;

if ( HashTabOf (i) == fcode ) {
ent = CodeTabOf (i);
continue;
}
if ( (long)HashTabOf (i) > 0 )
goto probe;
nomatch:
output ( (code_int) ent );
++out_count;
ent = c;
#ifdef SIGNED_COMPARE_SLOW
if ( (unsigned) free_ent < (unsigned) maxmaxcode) {
#else /*SIGNED_COMPARE_SLOW*/
if ( free_ent < maxmaxcode ) { /* } */
#endif /*SIGNED_COMPARE_SLOW*/
CodeTabOf (i) = free_ent++; /* code -> hashtable */
HashTabOf (i) = fcode;
} else
cl_block();
}
/*
* Put out the final code.
*/
output( (code_int)ent );
++out_count;
output( (code_int) EOFCode );
}

/*****************************************************************
* TAG( output )
*
* Output the given code.
* Inputs:
* code: A n_bits-bit integer. If == -1, then EOF. This assumes
* that n_bits =< (long)wordsize - 1.
* Outputs:
* Outputs code to the file.
* Assumptions:
* Chars are 8 bits long.
* Algorithm:
* Maintain a BITS character long buffer (so that 8 codes will
* fit in it exactly). Use the VAX insv instruction to insert each
* code in turn. When the buffer fills up empty it and start over.
*/

static unsigned long cur_accum = 0;
static int cur_bits = 0;

static unsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,
0x001F, 0x003F, 0x007F, 0x00FF,
0x01FF, 0x03FF, 0x07FF, 0x0FFF,
0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };

static void
output( code )
code_int code;
{
cur_accum &= masks[ cur_bits ];

if( cur_bits > 0 )
cur_accum ¦= ((long)code << cur_bits);
else
cur_accum = code;

cur_bits += n_bits;

while( cur_bits >= 8 ) {
char_out( (unsigned int)(cur_accum & 0xff) );
cur_accum >>= 8;
cur_bits -= 8;
}

/*
* If the next entry is going to be too big for the code size,
* then increase it, if possible.
*/
if ( free_ent > maxcode ¦¦ clear_flg ) {

if( clear_flg ) {

maxcode = MAXCODE (n_bits = g_init_bits);
clear_flg = 0;

} else {

++n_bits;
if ( n_bits == maxbits )
maxcode = maxmaxcode;
else
maxcode = MAXCODE(n_bits);
}
}

if( code == EOFCode ) {
/*
* At EOF, write the rest of the buffer.
*/
while( cur_bits > 0 ) {
char_out( (unsigned int)(cur_accum & 0xff) );
cur_accum >>= 8;
cur_bits -= 8;
}

flush_char();

fflush( g_outfile );

if( ferror( g_outfile ) )
writeerr();
}
}

/*
* Clear out the hash table
*/
static void
cl_block () /* table clear for block compress */
{

cl_hash ( (count_int) hsize );
free_ent = ClearCode + 2;
clear_flg = 1;

output( (code_int)ClearCode );
}

static void
cl_hash(hsize) /* reset code table */
register count_int hsize;
{

register count_int *htab_p = htab+hsize;

register long i;
register long m1 = -1;

i = hsize - 16;
do { /* might use Sys V memset(3) here */
*(htab_p-16) = m1;
*(htab_p-15) = m1;
*(htab_p-14) = m1;
*(htab_p-13) = m1;
*(htab_p-12) = m1;
*(htab_p-11) = m1;
*(htab_p-10) = m1;
*(htab_p-9) = m1;
*(htab_p-8) = m1;
*(htab_p-7) = m1;
*(htab_p-6) = m1;
*(htab_p-5) = m1;
*(htab_p-4) = m1;
*(htab_p-3) = m1;
*(htab_p-2) = m1;
*(htab_p-1) = m1;
htab_p -= 16;
} while ((i -= 16) >= 0);

for ( i += 16; i > 0; --i )
*--htab_p = m1;
}

static void
writeerr()
{
err( "error writing output file" );
}

/******************************************************************************
*
* GIF Specific routines
*
******************************************************************************/

/*
* Number of characters so far in this 'packet'
*/
static int a_count;

/*
* Set up the 'byte output' routine
*/
static void char_init(){
a_count = 0;
}

/*
* Define the storage for the packet accumulator
*/
static char accum[ 256 ];

/*
* Add a character to the end of the current packet, and if it is 254
* characters, flush the packet to disk.
*/
static void
char_out( int c ){
accum[ a_count++ ] = c;
if( a_count >= 254 )
flush_char();
}
/*
* Flush the packet to disk, and reset the accumulator
*/
static void flush_char(){
if( a_count > 0 ) {
fputc( a_count, g_outfile );
fwrite_chk( accum, 1, a_count, g_outfile );
a_count = 0;
}
}
/*
**
** Based on GIFENCOD by David Rowley <mgardi@watdscu.waterloo.edu>.A
** Lempel-Zim compression based on "compress".
**
** Modified by Marcel Wijkstra <wijkstra@fwi.uva.nl>
**
**
** Copyright (C) 1989 by Jef Poskanzer.
**
** The Graphics Interchange Format(c) is the Copyright property of
** CompuServe Incorporated. GIF(sm) is a Service Mark property of
** CompuServe Incorporated.
*/
/****************************************************************************** Windows functions, types, and definitions *
* Version 3.10 *
* Copyright (c) 1985-1992, Microsoft Corp. All rights reserved. *
*******************************************************************************
*
*(C)1996 Ephraim Cohen--subject to the above,
** permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notices appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation. This software is provided "as is" without express or
** implied warranty.
**
*/




回复人: CFree(自由从哪派生?) (2001-7-24 11:20:42) 得0分
关注。
回复人: bzshow(神啊,求求我吧!)) (2001-7-24 11:23:36) 得0分
错了, 上个是bmp转gif的源代码.
下面一个才是gif转bmp的原码
回复人: bzshow(神啊,求求我吧!)) (2001-7-24 11:26:02) 得0分
/* gif2bmp.c -- See end-of-file for (C)*/
/* This was written for Microsoft 32-bit-integer compilers--it
* should compile with
* cl gif2bmp.c
* to produce the executable gif2bmp.exe
*
* The Microsoft oddities are:
* The funny include files -- they may be omitted on compilers
* that can not find them (stdio.h better be there, however)
* #pragma pack(1) -- This forces the BITMAPFILEHEADER structure
* to be the same length in memory as in files (otherwise, the structure
* is padded out to be a multiple of 8? bytes long
* Note that Microsoft uses all-caps for typedefs. Ugh.
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <math.h>
typedef unsigned char byte;
typedef unsigned short WORD;
typedef unsigned long DWORD;

#pragma pack(1)
typedef struct tagRGBQUAD {
byte rgbBlue;
byte rgbGreen;
byte rgbRed;
byte rgbReserved;
} RGBQUAD;
typedef struct tagBITMAPFILEHEADER {
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} BITMAPFILEHEADER;
typedef BITMAPFILEHEADER *PBITMAPFILEHEADER;

typedef struct tagBITMAPINFOHEADER{
DWORD biSize;
DWORD biWidth;
DWORD biHeight;
WORD biPlanes;
WORD biBitCount;

DWORD biCompression;
DWORD biSizeImage;
DWORD biXPelsPerMeter;
DWORD biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} BITMAPINFOHEADER;

BITMAPFILEHEADER hdr;
BITMAPINFOHEADER bi;
long wib;
RGBQUAD cmap[256];
FILE *fp;
int bit8= 0;

static int dib_wib(int bitcount, int wi){
switch (bitcount){
case 1: wi= (wi+31) >> 3; break;
case 4: wi= (wi+7) >> 1; break;
case 8: wi= wi+3; break;
case 16:wi= (wi*2)+3; break;
case 24:wi= (wi*3)+3; break;
case 32:return wi*4;
}
return wi & ~3;
}
void pm_error(char *msg){
fprintf(stderr, "%s\n", msg);
exit(5);
}
/* Output .bmp header */
int spew_header(int wi, int hi, int n, RGBQUAD *cmap){
/* Writes to the global fp */

if(n>16 ¦¦ bit8)
bi.biBitCount= 8;
else if(n>2)
bi.biBitCount= 4;
else
bi.biBitCount= 1;
n= 1 << ((int)bi.biBitCount);
bi.biSize= sizeof(bi);
bi.biWidth= wi;
bi.biHeight= hi;
bi.biPlanes= 1;
bi.biCompression= 0;
wib= dib_wib((int)bi.biBitCount, (int)bi.biWidth);
bi.biSizeImage= bi.biHeight * wib;
bi.biClrUsed= n;
bi.biClrImportant= n;
bi.biXPelsPerMeter= 0;
bi.biYPelsPerMeter= 0;

hdr.bfType= 0x4d42; /* BM */
hdr.bfReserved1= 0;
hdr.bfReserved2= 0;
hdr.bfOffBits = sizeof(hdr) + bi.biSize + n*sizeof(RGBQUAD);
hdr.bfSize= hdr.bfOffBits + bi.biSizeImage;

fwrite(&hdr,1,sizeof(hdr),fp);
fwrite(&bi, 1, sizeof(bi), fp);
if(n>0)
fwrite(cmap, sizeof(RGBQUAD), n, fp);
return 1;
}

#define MAXCOLORMAPSIZE 256

#define TRUE 1
#define FALSE 0

#define CM_RED 0
#define CM_GREEN 1
#define CM_BLUE 2

#define MAX_LWZ_BITS 12

#define INTERLACE 0x40
#define LOCALCOLORMAP 0x80
#define BitSet(byte, bit) (((byte) & (bit)) == (bit))

#define ReadOK(file,buffer,len) (fread(buffer, len, 1, file) != 0)

#define LM_to_uint(a,b) (((b)<<8)¦(a))

static struct {
unsigned int Width;
unsigned int Height;
RGBQUAD ColorMap[MAXCOLORMAPSIZE];
unsigned int BitPixel;
unsigned int ColorResolution;
unsigned int Background;
unsigned int AspectRatio;
/*
**
*/
int GrayScale;
} GifScreen;

static struct {
int transparent;
int delayTime;
int inputFlag;
int disposal;
} Gif89 = { -1, -1, -1, 0 };

int verbose;
int showComment;

static void ReadGIF ( FILE *fd, int imageNumber );
static int ReadColorMap ( FILE *fd, int number, RGBQUAD *b);
static int DoExtension ( FILE *fd, int label );
static int GetDataBlock ( FILE *fd, unsigned char *buf );
static int GetCode ( FILE *fd, int code_size, int flag );
static int LWZReadByte ( FILE *fd, int flag, int input_code_size );
static void ReadImage ( FILE *fd, int len, int height, RGBQUAD *cmap, int gray, int interlace, int ignore );

char *note[]= {
"Usage: oldfile.gif newfile.bmp",
"Convert gif image to bmp image",
"Options:",
"-8 Output 8-bit per pixel .bmp image",
"-v Verbose",
"-c Comments",
"-i # Get the #th image in the gif",
0};
int main(int argc, char **argv){
FILE *in;
int imageNumber;
char *cp;
char *srcname= 0;
char *dstname= 0;

imageNumber = 1;
verbose = FALSE;
showComment = FALSE;

while(cp= *++argv)if(*cp++=='-')switch(*cp++){
case '8': bit8= 1; break;
case 'v': verbose= TRUE;
case 'c': showComment= TRUE;
break;
case 'i': imageNumber= atoi(*++argv); break;
default: err: for(argv= note; *argv; ++argv)
fprintf(stderr, "%s\n", *argv);
exit(0);
}else if(srcname==0)
srcname= *argv;
else if(dstname==0)
dstname= *argv;
else goto err;
if(dstname==0)
goto err;

in= fopen(srcname, "rb");
if(in==0){
perror(srcname);
exit(1);
}
fp= fopen(dstname, "wb");
if(fp==0){
perror(dstname);
exit(1);
}
ReadGIF(in, imageNumber);
fclose(in);
fclose(fp);
return 0;
}
static void ReadGIF(FILE *fd, int imageNumber){
unsigned char buf[16];
unsigned char c;
static RGBQUAD localColorMap[MAXCOLORMAPSIZE];
int useGlobalColormap;
int bitPixel;
int imageCount = 0;
char version[4];

if (! ReadOK(fd,buf,6))
pm_error("error reading magic number" );

if (strncmp((char *)buf,"GIF",3) != 0)
pm_error("not a GIF file" );

strncpy(version, (char *)buf + 3, 3);
version[3] = '\0';

if ((strcmp(version, "87a") != 0) && (strcmp(version, "89a") != 0))
pm_error("bad version number, not '87a' or '89a'" );

if (! ReadOK(fd,buf,7))
pm_error("failed to read screen descriptor" );

GifScreen.Width = LM_to_uint(buf[0],buf[1]);
GifScreen.Height = LM_to_uint(buf[2],buf[3]);
GifScreen.BitPixel = 2<<(buf[4]&0x07);
GifScreen.ColorResolution = (((buf[4]&0x70)>>3)+1);
GifScreen.Background = buf[5];
GifScreen.AspectRatio = buf[6];

if (BitSet(buf[4], LOCALCOLORMAP)) { /* Global Colormap */
if (ReadColorMap(fd,GifScreen.BitPixel, GifScreen.ColorMap))
pm_error("error reading global colormap" );
}
/*
if (GifScreen.AspectRatio != 0 && GifScreen.AspectRatio != 49) {
float r;
r = ( (float) GifScreen.AspectRatio + 15.0 ) / 64.0;
fprintf(stderr,"warning - non-square pixels; to fix do a 'pnmscale -%cscale %g'\n",
r < 1.0 ? 'x' : 'y',
r < 1.0 ? 1.0 / r : r );
}
*/
for (;;) {
if (! ReadOK(fd,&c,1))
pm_error("EOF / read error on image data" );

if (c == ';') { /* GIF terminator */
if (imageCount < imageNumber){
fprintf(stderr, "only %d image%s found in file\n",
imageCount, imageCount>1?"s":"" );
exit(1);
}
return;
}

if (c == '!') { /* Extension */
if (! ReadOK(fd,&c,1))
pm_error("OF / read error on extention function code");
DoExtension(fd, c);
continue;
}

if (c != ',') { /* Not a valid start character */
fprintf(stderr,"bogus character 0x%02x, ignoring\n", (int) c );
continue;
}

++imageCount;

if (! ReadOK(fd,buf,9))
pm_error("couldn't read left/top/width/height");

useGlobalColormap = ! (buf[8] & LOCALCOLORMAP);

bitPixel = 1<<((buf[8]&0x07)+1);

if (! useGlobalColormap) {
if (ReadColorMap(fd, bitPixel, localColorMap))
pm_error("error reading local colormap" );
ReadImage(fd, LM_to_uint(buf[4],buf[5]),
LM_to_uint(buf[6],buf[7]),
localColorMap, bitPixel,
buf[8]&INTERLACE, imageCount != imageNumber);
} else {
ReadImage(fd, LM_to_uint(buf[4],buf[5]),
LM_to_uint(buf[6],buf[7]),
GifScreen.ColorMap, GifScreen.BitPixel,
buf[8]&INTERLACE, imageCount != imageNumber);
}

}
}

static int ReadColorMap(FILE *fd, int number, RGBQUAD *buffer){
int i;
unsigned char rgb[3];

for (i = 0; i < number; ++i, buffer++) {
if (! ReadOK(fd, rgb, sizeof(rgb)))
pm_error("bad colormap" );
buffer->rgbRed= rgb[0];
buffer->rgbGreen= rgb[1];
buffer->rgbBlue= rgb[2];
buffer->rgbReserved= 0;
}
return 0;
}
static int DoExtension(FILE *fd, int label){
static char buf[256];
char *str;

switch (label) {
case 0x01: /* Plain Text Extension */
str = "Plain Text Extension";
#ifdef notdef
if (GetDataBlock(fd, (unsigned char*) buf) == 0)
;

lpos = LM_to_uint(buf[0], buf[1]);
tpos = LM_to_uint(buf[2], buf[3]);
width = LM_to_uint(buf[4], buf[5]);
height = LM_to_uint(buf[6], buf[7]);
cellw = buf[8];
cellh = buf[9];
foreground = buf[10];
background = buf[11];

while (GetDataBlock(fd, (unsigned char*) buf) != 0) {
PPM_ASSIGN(image[ypos][xpos],
cmap[CM_RED][v],
cmap[CM_GREEN][v],
cmap[CM_BLUE][v]);
++index;
}

return FALSE;
#else
break;
#endif
case 0xff: /* Application Extension */
str = "Application Extension";
GetDataBlock(fd, (unsigned char*) buf);
if (showComment){
fprintf(stderr, "Application Extension: %c%c%c%c%c%c%c%c ",
buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7]);
fprintf(stderr, " Authentication Code=)%02x %02x %02x\n",
buf[8], buf[9], buf[10]);
}
break;
case 0xfe: /* Comment Extension */
str = "Comment Extension";
while (GetDataBlock(fd, (unsigned char*) buf) != 0) {
if (showComment)
fprintf(stderr,"gif comment: %s\n", buf );
}
return FALSE;
case 0xf9: /* Graphic Control Extension */
str = "Graphic Control Extension";
(void) GetDataBlock(fd, (unsigned char*) buf);
Gif89.disposal = (buf[0] >> 2) & 0x7;
Gif89.inputFlag = (buf[0] >> 1) & 0x1;
Gif89.delayTime = LM_to_uint(buf[1],buf[2]);
if ((buf[0] & 0x1) != 0)
Gif89.transparent = buf[3];

while (GetDataBlock(fd, (unsigned char*) buf) != 0)
;
return FALSE;
default:
str = buf;
sprintf(buf, "UNKNOWN (0x%02x)", label);
break;
}

fprintf(stderr,"got a '%s' extension\n", str );

while (GetDataBlock(fd, (unsigned char*) buf) != 0)
;

return FALSE;
}
int ZeroDataBlock = FALSE;

static int GetDataBlock(FILE *fd, unsigned char *buf){
unsigned char count;

if (! ReadOK(fd,&count,1)) {
fprintf(stderr,"error in getting DataBlock size\n" );
return -1;
}

ZeroDataBlock = count == 0;

if ((count != 0) && (! ReadOK(fd, buf, count))) {
fprintf(stderr,"error in reading DataBlock\n" );
return -1;
}

return count;
}
static int GetCode(FILE *fd, int code_size, int flag){
static unsigned char buf[280];
static int curbit, lastbit, done, last_byte;
int i, j, ret;
unsigned char count;

if (flag) {
curbit = 0;
lastbit = 0;
done = FALSE;
return 0;
}

if ( (curbit+code_size) >= lastbit) {
if (done) {
if (curbit >= lastbit)
pm_error("ran off the end of my bits" );
return -1;
}
buf[0] = buf[last_byte-2];
buf[1] = buf[last_byte-1];

if ((count = GetDataBlock(fd, &buf[2])) == 0)
done = TRUE;

last_byte = 2 + count;
curbit = (curbit - lastbit) + 16;
lastbit = (2+count)*8 ;
}

ret = 0;
for (i = curbit, j = 0; j < code_size; ++i, ++j)
ret ¦= ((buf[ i / 8 ] & (1 << (i % 8))) != 0) << j;

curbit += code_size;

return ret;
}
static int LWZReadByte(FILE *fd, int flag, int input_code_size){
static int fresh = FALSE;
int code, incode;
static int code_size, set_code_size;
static int max_code, max_code_size;
static int firstcode, oldcode;
static int clear_code, end_code;
static int table[2][(1<< MAX_LWZ_BITS)];
static int stack[(1<<(MAX_LWZ_BITS))*2], *sp;
register int i;

if (flag) {
set_code_size = input_code_size;
code_size = set_code_size+1;
clear_code = 1 << set_code_size ;
end_code = clear_code + 1;
max_code_size = 2*clear_code;
max_code = clear_code+2;

GetCode(fd, 0, TRUE);

fresh = TRUE;

for (i = 0; i < clear_code; ++i) {
table[0][i] = 0;
table[1][i] = i;
}
for (; i < (1<<MAX_LWZ_BITS); ++i)
table[0][i] = table[1][0] = 0;

sp = stack;

return 0;
} else if (fresh) {
fresh = FALSE;
do {
firstcode = oldcode =
GetCode(fd, code_size, FALSE);
} while (firstcode == clear_code);
return firstcode;
}

if (sp > stack)
return *--sp;

while ((code = GetCode(fd, code_size, FALSE)) >= 0) {
if (code == clear_code) {
for (i = 0; i < clear_code; ++i) {
table[0][i] = 0;
table[1][i] = i;
}
for (; i < (1<<MAX_LWZ_BITS); ++i)
table[0][i] = table[1][i] = 0;
code_size = set_code_size+1;
max_code_size = 2*clear_code;
max_code = clear_code+2;
sp = stack;
firstcode = oldcode =
GetCode(fd, code_size, FALSE);
return firstcode;
} else if (code == end_code) {
int count;
unsigned char buf[260];

if (ZeroDataBlock)
return -2;

while ((count = GetDataBlock(fd, buf)) > 0)
;

if (count != 0)
fprintf(stderr,"missing EOD in data stream (common occurence)\n");
return -2;
}

incode = code;

if (code >= max_code) {
*sp++ = firstcode;
code = oldcode;
}

while (code >= clear_code) {
*sp++ = table[1][code];
if (code == table[0][code])
pm_error("circular table entry BIG ERROR");
code = table[0][code];
}

*sp++ = firstcode = table[1][code];

if ((code = max_code) <(1<<MAX_LWZ_BITS)) {
table[0][code] = oldcode;
table[1][code] = firstcode;
++max_code;
if ((max_code >= max_code_size) &&
(max_code_size < (1<<MAX_LWZ_BITS))) {
max_code_size *= 2;
++code_size;
}
}

oldcode = incode;

if (sp > stack)
return *--sp;
}
return code;
}
static void ReadImage(FILE *fd, int len, int height, RGBQUAD *cmap,
int bpp, int interlace, int ignore){
unsigned char c;
int v;
int xpos = 0, ypos = 0, pass = 0;
unsigned char *scanline;

/*
** Initialize the Compression routines
*/
if (! ReadOK(fd,&c,1))
pm_error("EOF / read error on image data" );

if (LWZReadByte(fd, TRUE, c) < 0)
pm_error("error reading image" );

/*
** If this is an "uninteresting picture" ignore it.
*/
if (ignore) {
if (verbose)
fprintf(stderr,"skipping image...\n" );

while (LWZReadByte(fd, FALSE, c) >= 0)
;
return;
}
if ((scanline= (unsigned char *)malloc(len)) == NULL)
pm_error("couldn't alloc space for image" );


if (verbose)
fprintf(stderr,"reading %d by %d%s GIF image\n",
len, height, interlace ? " interlaced" : "" );
spew_header(len, height, bpp, cmap);

/* Fill the whole file with junk */
for(v= 0; v<height; v++)
fwrite(scanline, 1, (int)wib, fp);

while (ypos<height && (v = LWZReadByte(fd,FALSE,c)) >= 0) {
switch(bi.biBitCount){
case 1:
if(v)
scanline[xpos>>3] ¦= 128 >> (xpos&7);
else
scanline[xpos>>3] &= 0xff7f >> (xpos&7);
break;
case 4:
if(xpos&1)
scanline[xpos>>1] ¦= v&15;
else
scanline[xpos>>1] = (v&15) << 4;
break;
case 8:
scanline[xpos]= v;
break;
}
++xpos;
if (xpos == len) {
fseek(fp, -(ypos+1)*wib, SEEK_END);
fwrite(scanline, 1, (int)wib, fp);
xpos = 0;
if (interlace) {
static int dpass[]= {8,8,4,2};
ypos += dpass[pass];
if (ypos >= height) {
static int restart[]= {0,4,2,1,32767};
ypos= restart[++pass];
}
} else
++ypos;
}
}
if(LWZReadByte(fd, FALSE,c) >= 0)
fprintf(stderr,"too much input data, ignoring extra...\n");
}
/* +-------------------------------------------------------------------+ */
/* ¦ Copyright 1990, 1991, 1993, David Koblas. (koblas@netcom.com) ¦ */
/* +-------------------------------------------------------------------+ */
/****************************************************************************** Windows functions, types, and definitions *
* Version 3.10 *
* Copyright (c) 1985-1992, Microsoft Corp. All rights reserved. *
*******************************************************************************
*
*(C)1996 Ephraim Cohen--subject to the above
** permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notices appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation. This software is provided "as is" without express or
** implied warranty.
*/

hujun614 2002-01-12
  • 打赏
  • 举报
回复
图象操作类,支持BMP JPEG GIF PNG TIFF MNG ICO
http://www.vcunion.net/cx_image.zip
MHB 2002-01-12
  • 打赏
  • 举报
回复
我正好也要,及時雨,謝謝

16,551

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Creator Browser
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧