I'd been starting at this for hours and can't figure out what I'm doing wrong. To scale for the horizontal I put fwrite() in a for loop repeating n
times for each pixel. To scale vertically I put the whole code in another for loop in where it goes back to the start of the old scanline, re-reading and re-rewriting it.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include "bmp.h"
int main(int argc, char* argv[])
{
// ensure proper usage
if (argc != 4)
{
printf("Usage: ./resize n infile outfile");
return 1;
}
// remember filenames
char* infile = argv[2];
char* outfile = argv[3];
int n = atoi(argv[1]);
if (n <= 0 && n>= ((2^32)-1))
{
printf("n should be less than 2^32-1");
return 2;
}
// open input file
FILE* inptr = fopen(infile, "r");
if (inptr == NULL)
{
printf("Could not open %s.\n", infile);
return 3;
}
// open output file
FILE* outptr = fopen(outfile, "w");
if (outptr == NULL)
{
fclose(inptr);
fprintf(stderr, "Could not create %s.\n", outfile);
return 4;
}
// 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;
}
//old
int oldWidth = bi.biWidth;
int oldHeight = abs(bi.biHeight);
int oldPadding = (4 - (oldWidth * sizeof(RGBTRIPLE)) % 4) % 4; //padding = 3
//new
bi.biWidth *= n;
bi.biHeight *= n;
int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4; //padding = 3
bi.biSizeImage = ((sizeof(RGBTRIPLE) * bi.biWidth) + 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; i < oldHeight; i++) //oldHeight = 3
{
for(int a=0; a<n;a++) //resizing vertically
{
// iterate over pixels in scanline
for (int j = 0; j < oldWidth; j++) //bi.biWidth = 6
{
// temporary storage
RGBTRIPLE triple;
// read RGB triple from infile
fread(&triple, sizeof(RGBTRIPLE), 1, inptr);
// write RGB triple to outfile (repeated n times for each pixel)
for(int r=0; r< n ; r++)
fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
}
// skip over padding, if any
fseek(inptr, oldPadding, SEEK_CUR); //skipping padding of infile (3)
// then add it back (to demonstrate how)
for (int k = 0; k < padding; k++) //new padding = 2
{
fputc(0x00, outptr);
}
fseek(inptr, -(oldWidth+oldPadding), SEEK_CUR); //going back
}
}
// close infile
fclose(inptr);
// close outfile
fclose(outptr);
// that's all folks
return 0;
}
Output:
~/workspace/pset4/bmp/ $ ./resize 2 small.bmp t.bmp
Any help would be appreciated.