Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * copy.c
- *
- * Computer Science 50
- * Problem Set 4
- *
- * Copies a BMP piece by piece, just because.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include "bmp.h"
- int main(int argc, char* argv[])
- {
- // ensure proper usage
- if (argc != 4)
- {
- printf("Usage: ./copy infile outfile\n");
- return 1;
- }
- // remember filenames
- int n = atoi(argv[1]);
- 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;
- }
- //Save original values just in case (UNLOCK AS NEEDED OR ELSE STUPID UNUSED VARIABLE ERROR)
- LONG old_biWidth = bi.biWidth;
- LONG old_biHeight = bi.biHeight;
- int old_padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
- //DWORD old_biSizeImage = bi.biSizeImage;
- //DWORD old_bfSize = bf.bfSize;
- //Modify headers for outfile
- bi.biWidth = bi.biWidth * n;
- bi.biHeight = bi.biHeight * n;
- int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
- 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);
- // temporary storage variables
- RGBTRIPLE triple;
- RGBTRIPLE array[bi.biWidth]; //size of modified height
- // iterate over infile's scanlines
- for (int i = 0; i < abs(old_biHeight); i++)
- {
- // copy row into array
- for (int j = 0; j < old_biWidth; j++)
- {
- // read RGB triple from infile
- fread(&triple, sizeof(RGBTRIPLE), 1, inptr);
- array[j] = triple; //put it in an array
- }
- //skip over any padding
- fseek(inptr, old_padding, SEEK_CUR);
- for (int w = 0; w < bi.biWidth; w++)
- {
- triple = array[w];
- fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
- }
- //add padding new padding
- for (int k = 0; k < padding; k++)
- {
- fputc(0x00, outptr);
- }
- }
- // close infile
- fclose(inptr);
- // close outfile
- fclose(outptr);
- // that's all folks
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement