I am working on resize for PSET4, and more specifically I'm at the point of working out the horizontal resizing (in other words, don't look for the vertical resizing, it's not even started yet). I can get the first line to resize accurately, however after that it starts producing random seeming colors - although those do seem to repeat themselves as desired. : ) But what is causing this random colorization?
Here is my code:
/** * Copies and resizes a BMP piece by piece. */
include
include
include "bmp.h"
int main(int argc, char* argv[]) { // ensure proper usage if (argc != 4) { printf("Usage: ./copy infile outfile\n"); return 1; }
//check to make sure the scale factor is within acceptable range
int scale = atoi(argv[1]);
if (scale < 1 || scale > 100)
{
printf("Scale of resize must be between 1 and 100.\n");
return 1;
}
// remember filenames
char* infile = argv[2];
char* outfile = argv[3];
// open input file
FILE* inptr = fopen(infile, "r");
if (inptr == NULL)
{
printf("Could not open %s.\n", infile);
return 2;
}
// open output file
FILE* outptr = fopen(outfile, "w");
if (outptr == NULL)
{
fclose(inptr);
fprintf(stderr, "Could not create %s.\n", outfile);
return 3;
}
// read infile's BITMAPFILEHEADER
BITMAPFILEHEADER bf;
fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);
// read infile's BITMAPINFOHEADER
BITMAPINFOHEADER bi;
fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);
// ensure infile is (likely) a 24-bit uncompressed BMP 4.0
if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
bi.biBitCount != 24 || bi.biCompression != 0)
{
fclose(outptr);
fclose(inptr);
fprintf(stderr, "Unsupported file format.\n");
return 4;
}
//Copy header, then alter and use updated version for outfile;
BITMAPFILEHEADER new_file = bf;
BITMAPINFOHEADER new_info = bi;
new_info.biWidth = bi.biWidth*scale;
new_info.biHeight = bi.biHeight*scale;
// determine padding for scanlines
int padding = (4 - (new_info.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
//resize header info
new_info.biSizeImage = (new_info.biSizeImage*scale+padding)*scale; //CHECK
// write outfile's BITMAPFILEHEADER
fwrite(&new_file, sizeof(BITMAPFILEHEADER), 1, outptr);
// write outfile's BITMAPINFOHEADER
fwrite(&new_info, sizeof(BITMAPINFOHEADER), 1, outptr);
// iterate over infile's scanlines
for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
{
// iterate over pixels in scanline
for (int j = 0; j < bi.biWidth; j++)
{
// temporary storage
RGBTRIPLE triple;
// read RGB triple from infile
fread(&triple, sizeof(RGBTRIPLE), 1, inptr);
// write RGB triple to outfile
for (int k = 0; k < scale; k++)
{
fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
}
}
// skip over padding, if any
fseek(inptr, padding, SEEK_CUR);
// then add it back (to demonstrate how)
for (int k = 0; k < padding; k++)
{
fputc(0x00, outptr);
}
}
// close infile
fclose(inptr);
// close outfile
fclose(outptr);
// that's all folks
return 0;
}