I'm struggled for 12 hours on resize problem. After trying for so long i reach to this result. The smiley BMP file looks well but it doesn't seem to be fully resized. When i try to resize small.bmp all the collors are distorted. I suppose there is among others a padding problem. PLease help me with this.
// Resizes a BMP file with a factor of n
#include <stdio.h>
#include <stdlib.h>
#include "bmp.h"
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 4)
{
fprintf(stderr, "Usage: resize queficient infile outfile\n");
return 1;
}
int n = atoi(argv[1]);
if (n < 1 || n > 100)
{
printf ("Resize queficient should 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)
{
fprintf(stderr, "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;
}
/* Update header info
*saving old information
*/
BITMAPINFOHEADER old_bi;
BITMAPFILEHEADER old_bf;
old_bi = bi;
old_bf = bf;
old_bi.biHeight = bi.biHeight;
old_bi.biWidth = bi.biWidth;
int old_padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
// assign new header
bi.biHeight = bi.biHeight * n;
bi.biWidth = bi.biWidth * n;
int new_padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
bi.biSizeImage = ((sizeof(RGBTRIPLE) * bi.biWidth) + new_padding) * abs(bi.biHeight);
bf.bfSize = bi.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
// write outfile's BITMAPFILEHEADER
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr);
// write outfile's BITMAPINFOHEADER
fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr);
// iterate over infile's scanlines
for (int i = 0, old_biHeight = abs(old_bi.biHeight); i < old_biHeight; i++)
{
RGBTRIPLE array_of_pixels[bi.biWidth];
// iterate over pixels in scanline
for (int j = 0; j < old_bi.biWidth; j++)
{
// temporary storage
RGBTRIPLE triple;
// read RGB triple from infile
fread(&triple, sizeof(RGBTRIPLE), 1, inptr);
for(int k = 0; k < n; k++)
{
array_of_pixels[k] = triple;
}
// write RGB triple to infile
for (int l = 0; l < n; l++)
{
fwrite(&array_of_pixels[l], sizeof(RGBTRIPLE), 1, outptr);
for(int m = 0; m < new_padding; m++)
{
fputc(0x00, outptr);
}
}
}
// skip over padding, if any
fseek(inptr, old_padding, SEEK_CUR);
}
// close infile
fclose(inptr);
// close outfile
fclose(outptr);
// success
return 0;
}