Copying BMP Header - c

I am trying to copy the header of one BMP file into another, checking that the file is 24-bit uncompressed. This is resulting in an error (via my if statement).
This is the structs used to hold the header data
typedef uint8_t BYTE;
typedef uint16_t WORD;
typedef uint32_t DWORD;
typedef int32_t LONG;
// Hold Bitmap File Header Information
typedef struct
{
WORD bfType; // File Type MUST BE BM
DWORD bfSize; // Bitmap File: Size in Bytes
WORD bfReserved1; // Reserved: MUST BE 0
WORD bfReserved2; // Reserved: MUST BE 0
DWORD bfOffBits; // Offset: Beginning of BITMAPFILEHEADER to Bitmap Bits
} BITMAPFILEHEADER;
// Hold Bitmap Info Header Information
typedef struct tagBITMAPINFOHEADER {
DWORD biSize; // Bytes required by the structure
LONG biWidth; // Specific the width of the bitmap in pixels
LONG biHeight; // Height of bitmap in pixels
WORD biPlanes; // Set number of planes to target device. HAS to be set to 1
WORD biBitCount; // Number of bits per pixel || Uncompressed Formats Average Number Of Bits Per Pixel
DWORD biCompression; // Type of compression
DWORD biSizeImage; // Size of image in bytes
LONG biXPelsPerMeter; // Horizitonal resolution in pixels per meter
LONG biYPelsPerMeter; // Vertical resolution in pixels per meter
DWORD biClrUsed; // Specifies no. of colour indices in the color table
DWORD biClrImportant; // Speifiies no. of colours that are important for displaying bitmap
} BITMAPINFOHEADER, * LPBITMAPINFOHEADER, * PBITMAPINFOHEADER;
FILE* Original = fopen(argv[1], "rb");
if (Original == NULL)
{
printf("ERROR: Couldn't open file\n");
printf("Check File Name\n\n");
}
// Read Header
BITMAPFILEHEADER BF;
fread(&BF, sizeof(BITMAPFILEHEADER), ONCE, Original); // Read File Header
BITMAPINFOHEADER BI;
fread(&BI, sizeof(BITMAPINFOHEADER), ONCE, Original); // Read Info Header
// Check File -> 24-Bit Uncompressed
if (BF.bfType != 0x4D42 || BF.bfOffBits != 54 ||
BI.biSize != 40 || BI.biBitCount != 24 || BI.biCompression != 0)
{
printf("ERROR: Incorrect File Type\n");
printf("Check Bitmap Header!\n\n");
fclose(Original);
}
I have tried printf the struct data and I am even getting the wrong numbers inside of those, such as
bfType: 19778
bfOffBits: 8126464
biSize: 83886080
biBitCount: 0
biCompression: -83886080

Related

Accessing a BMP file that has been loaded in

I have some code that I found that reads in a .bmp file to my program, and I want to be able to access this file to draw it in a direct2d graphics program that I already have. Is this code set up in a way where I could do that or is it more for getting information about the .bmp file? Basically I just want to know if I can access the .bmp file using this code or if this is not set up for that.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define DATA_OFFSET_OFFSET 0x000A
#define WIDTH_OFFSET 0x0012
#define HEIGHT_OFFSET 0x0016
#define BITS_PER_PIXEL_OFFSET 0x001C
#define HEADER_SIZE 14
#define INFO_HEADER_SIZE 40
#define NO_COMPRESION 0
#define MAX_NUMBER_OF_COLORS 0
#define ALL_COLORS_REQUIRED 0
typedef unsigned int int32;
typedef short int16;
typedef unsigned char byte;
//***Inputs*****
//fileName: The name of the file to open
//***Outputs****
//pixels: A pointer to a byte array. This will contain the pixel data
//width: An int pointer to store the width of the image in pixels
//height: An int pointer to store the height of the image in pixels
//bytesPerPixel: An int pointer to store the number of bytes per pixel that are used in the image
void ReadImage(const char *fileName,byte **pixels, int32 *width, int32 *height, int32 *bytesPerPixel)
{
//Open the file for reading in binary mode
FILE *imageFile = fopen(fileName, "rb");
//Read data offset
int32 dataOffset;
fseek(imageFile, DATA_OFFSET_OFFSET, SEEK_SET);
fread(&dataOffset, 4, 1, imageFile);
//Read width
fseek(imageFile, WIDTH_OFFSET, SEEK_SET);
fread(width, 4, 1, imageFile);
//Read height
fseek(imageFile, HEIGHT_OFFSET, SEEK_SET);
fread(height, 4, 1, imageFile);
//Read bits per pixel
int16 bitsPerPixel;
fseek(imageFile, BITS_PER_PIXEL_OFFSET, SEEK_SET);
fread(&bitsPerPixel, 2, 1, imageFile);
//Allocate a pixel array
*bytesPerPixel = ((int32)bitsPerPixel) / 8;
//Rows are stored bottom-up
//Each row is padded to be a multiple of 4 bytes.
//We calculate the padded row size in bytes
int paddedRowSize = (int)(4 * ceil((float)(*width) / 4.0f))*(*bytesPerPixel);
//We are not interested in the padded bytes, so we allocate memory just for
//the pixel data
int unpaddedRowSize = (*width)*(*bytesPerPixel);
//Total size of the pixel data in bytes
int totalSize = unpaddedRowSize*(*height);
*pixels = (byte*)malloc(totalSize);
//Read the pixel data Row by Row.
//Data is padded and stored bottom-up
int i = 0;
//point to the last row of our pixel array (unpadded)
byte *currentRowPointer = *pixels+((*height-1)*unpaddedRowSize);
for (i = 0; i < *height; i++)
{
//put file cursor in the next row from top to bottom
fseek(imageFile, dataOffset+(i*paddedRowSize), SEEK_SET);
//read only unpaddedRowSize bytes (we can ignore the padding bytes)
fread(currentRowPointer, 1, unpaddedRowSize, imageFile);
//point to the next row (from bottom to top)
currentRowPointer -= unpaddedRowSize;
}
fclose(imageFile);
}
int main()
{
byte *pixels;
int32 width;
int32 height;
int32 bytesPerPixel;
ReadImage("img.bmp", &pixels, &width, &height,&bytesPerPixel);
free(pixels);
return 0;
}
Would I use pixels to then display the bitmap image?

Reading data from BMP file in C

I have a problem with reading pixels from bmp file. It might be something with padding at the end of row or the base64 padding. I have no clue. I've been struggling with this for some days and can't move on because the next task requires this one to be solved.
I only share important parts of the code, since reading bmp header worked fine (tests had 0 failures).
bmp.c
struct pixel* read_data(FILE* stream, const struct bmp_header* header){
if(stream == NULL || header == NULL){
return 0;
}
// w == 1 && p == 1; w == 2 && p == 2; w == 3 && p == 3; w == 4 && p == 0
int padding = header->width % 4;
int num_of_pixels = header->width * header->height;
struct pixel* Pixel[num_of_pixels];
fseek(stream, 54, SEEK_SET); //move 54B (header size)
int index_p = 0;
for(int i = 0; i < header->height; i++){
for(int j = 0; j < header->width; j++){
Pixel[index_p] = malloc(sizeof(struct pixel));
fread(&(Pixel[index_p]->blue), 1, 1, stream);
fread(&(Pixel[index_p]->green), 1, 1, stream);
fread(&(Pixel[index_p]->red), 1, 1, stream);
index_p++;
}
fseek(stream, padding, SEEK_CUR); //padding at the end of row
}
return *Pixel;
}
bmp.h
struct pixel {
uint8_t blue;
uint8_t green;
uint8_t red;
//uint8_t alpha;
} __attribute__((__packed__));
/**
* Read the pixels
*
* Reads the data (pixels) from stream representing the image. If the stream
* is not open or header is not provided, returns `NULL`.
*
* #param stream opened stream, where the image data are located
* #param header the BMP header structure
* #return the pixels of the image or `NULL` if stream or header are broken
*/
struct pixel* read_data(FILE* stream, const struct bmp_header* header);
header if needed (basically we use only 24bit color)
struct bmp_header{
uint16_t type; // "BM" (0x42, 0x4D)
uint32_t size; // file size
uint16_t reserved1; // not used (0)
uint16_t reserved2; // not used (0)
uint32_t offset; // offset to image data (54B)
uint32_t dib_size; // DIB header size (40B)
uint32_t width; // width in pixels
uint32_t height; // height in pixels
uint16_t planes; // 1
uint16_t bpp; // bits per pixel (24)
uint32_t compression; // compression type (0/1/2) 0
uint32_t image_size; // size of picture in bytes, 0
uint32_t x_ppm; // X Pixels per meter (0)
uint32_t y_ppm; // X Pixels per meter (0)
uint32_t num_colors; // number of colors (0)
uint32_t important_colors; // important colors (0)
} __attribute__((__packed__));
main.c I do not need to assign any variables to called functions because we have a program for testing this, I just have to call them in main
int main(){
struct bmp_header* header;
FILE *stream = fopen("./assets/square.2x3.bmp", "rb");
header = read_bmp_header(stream);
read_data(stream, header);
read_bmp(stream);
struct bmp_image* image;
image = malloc(sizeof(struct bmp_image));
free_bmp_image(image);
fclose(stream);
return 0;
}
testing (there are more tests, but this should be enough)
1:
FILE* stream = "Qk0+AAAAAAAAADYAAAAoAAAAAgAAAAEAAAABABgAAAAAAAgAAAAjLgAAIy4AAAAAAAAAAAAA/wAAAP8AAAA="; // base64 encoded stream
struct bmp_header* header = read_bmp_header(stream);
fseek(stream, offset, SEEK_SET);
Assertion 'read_data(stream, header) == "/wAAAP8A"' failed. [got "/wAAFctV"]
2:
FILE* stream = "Qk1GAAAAAAAAADYAAAAoAAAAAgAAAAIAAAABABgAAAAAABAAAAAjLgAAIy4AAAAAAAAAAAAA/wAAAAAAAAAAAP8A/wAAAA=="; // base64 encoded stream
struct bmp_header* header = read_bmp_header(stream);
fseek(stream, offset, SEEK_SET);
Assertion 'read_data(stream, header) == "/wAAAAAAAAD/AP8A"' failed. [got "/wAAAAAAAAAAAAAA"]
So after the "==" is expected result and in the brackets is my the result from my code. As I mentioned, it might be something with padding, since it starts well but doesn't end well.
Thanks for help.
Short Answer: Set padding to (4-((3*width)%4))%4
Long answer:
Your code included:
int padding = header->width % 4;
//Some lines of code
fseek(stream, padding, SEEK_CUR);
In a bitmap, padding is added until each row is a multiple of 4 bytes. You took padding as width % 4.
First off, each pixel takes 3 bytes(for rgb). So it should be (3*width)%4. Next, we need to subtract it from 4 bytes (Since padding is 4-pixels occupied). So padding would be 4-((3*width)%4). Another small modification, if (3*width)%4==0 then padding would come to be 4 (whereas, we expect it to be 0). So we take another mod4 just to be sure
So padding would come out to be (4-((3*width)%4))%4
EDIT:
As pointed out by user Craig Estey in the comments, its better to use sizeof(struct pixel) instead of 3

Expected exit code 0, not 1?

I submitted this problem set, but I'm unable to get a full mark grade because the exit code "is expected to be 0 and not a 1". However, if you take a look at the code (the recover.c file), the exit code is 0. What is wrong? The program accomplishes everything it was made for, which is to read through bits in a corrupted file and find the bits that make up a JPG file and write them in a separate file. The only problem I'm having is this aforementioned exit code issue. Please help!
recover.c file
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include "bmp.h"
int main (void){
FILE* card_ptr = fopen("card.raw","r");
if (card_ptr == NULL){
fprintf(stderr,"File Not Found!");
return 1;
}
BYTE buffer[512];
bool found_jpg = false;
FILE* new_jpg_ptr;
int file_counter = 0;
while(fread(buffer,1,512,card_ptr)!=0x00){
if(buffer[0]== 0xff && buffer[1]== 0xd8 && buffer[2]==0xff && (buffer[3] & 0xf0)== 0xe0){
if(!found_jpg){
char filename[8];
sprintf(filename, "%03i.jpg", file_counter++);
found_jpg = true;
new_jpg_ptr = fopen(filename,"w");
if(new_jpg_ptr == NULL){
return 2;
}
fwrite(buffer,1,512,new_jpg_ptr);
}
else {
fclose(new_jpg_ptr);
char filename[8];
sprintf(filename, "%03i.jpg", file_counter++);
found_jpg = true;
new_jpg_ptr = fopen(filename,"w");
if(new_jpg_ptr == NULL){
return 3;
}
fwrite(buffer,1,512, new_jpg_ptr);
}
}
else {
if(found_jpg){
fwrite(buffer,1,512, new_jpg_ptr);
}
}
}
fclose(new_jpg_ptr);
fclose(card_ptr);
return 0;
}
bmp.h file
/**
* BMP-related data types based on Microsoft's own.
*/
#include <stdint.h>
/**
* Common Data Types
*
* The data types in this section are essentially aliases for C/C++
* primitive data types.
*
* Adapted from https://msdn.microsoft.com/en-us/library/cc230309.aspx.
* See http://en.wikipedia.org/wiki/Stdint.h for more on stdint.h.
*/
typedef uint8_t BYTE;
typedef uint32_t DWORD;
typedef int32_t LONG;
typedef uint16_t WORD;
/**
* BITMAPFILEHEADER
*
* The BITMAPFILEHEADER structure contains information about the type, size,
* and layout of a file that contains a DIB [device-independent bitmap].
*
* Adapted from https://msdn.microsoft.com/en-us/library/dd183374(v=vs.85).aspx.
*/
typedef struct
{
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} __attribute__((__packed__))
BITMAPFILEHEADER;
/**
* BITMAPINFOHEADER
*
* The BITMAPINFOHEADER structure contains information about the
* dimensions and color format of a DIB [device-independent bitmap].
*
* Adapted from https://msdn.microsoft.com/en-us/library/dd183376(v=vs.85).aspx.
*/
typedef struct
{
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} __attribute__((__packed__))
BITMAPINFOHEADER;
/**
* RGBTRIPLE
*
* This structure describes a color consisting of relative intensities of
* red, green, and blue.
*
* Adapted from https://msdn.microsoft.com/en-us/library/dd162939(v=vs.85).aspx.
*/
typedef struct
{
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;
I experienced the same problem. My program worked as expected with no obvious reasons for a return code of 1. As you have, I had also included a header file with some definitions in it. Placing those definitions in the core file solved my problem. Perhaps if you move the needed definitions from your bmp.h file into recover.c, check50 will be able to compile.
My solution if you're interested.
// Recover any forgotten JPEGS from a given forensic image
# include <stdio.h>
# include <stdbool.h>
# include <stdint.h>
typedef uint8_t BYTE;
typedef struct
{
BYTE byte_1;
BYTE byte_2;
BYTE byte_3;
BYTE byte_4_min;
BYTE byte_4_max;
} __attribute__((__packed__))
SIG;
// declare helper function prototypes
int check_args(int argc, char *argv[]);
bool signature_is_present(BYTE potential_sig[4], SIG jpeg_sig);
SIG set_jpeg_signature(void);
// main program
int main (int argc, char *argv[])
{
// check input for validity
int check_args_value = check_args(argc, argv);
if (check_args_value != 0)
{
return check_args_value;
}
// call function to set default jpeg signature
SIG jpeg_sig = set_jpeg_signature();
// open buffers and declare other necessary variables for later use
BYTE FAT_block[512];
BYTE first_byte[1];
int signature_offset = -4;
int counter = 0;
// open forensic image
FILE * inptr = fopen(argv[1], "r");
FILE * outptr = NULL;
// loop through file searching for first '255'
while (fread(first_byte, sizeof(BYTE), 1, inptr) == 1)
{
// check if byte is 255, the first byte of a jpeg signature
if (*first_byte == jpeg_sig.byte_1)
{
// check for signature
BYTE possible_sig[4];
// back pointer up one byte to compensate for already discovered 255
fseek(inptr, -1, SEEK_CUR);
// read four bytes from file that could potentially be a signature.
fread(possible_sig, sizeof(possible_sig), 1, inptr);
if (signature_is_present(possible_sig, jpeg_sig))
{
// close previously open write file, if any.
if (outptr != NULL)
{
fclose(outptr);
//Increment counter for image signatures found.
counter++;
}
// setup name for image file
char file_name[8] = {};
snprintf(file_name, 8, "%.3i.jpg\n", counter);
// move pointer back 4 bytes after checking what they contain
fseek(inptr, signature_offset, SEEK_CUR);
//read FAT block from forensic image into buffer
fread(FAT_block, sizeof(FAT_block), 1, inptr);
// open new output file based on current signature
outptr = fopen(file_name, "w");
// write FAT block buffer to file
fwrite(FAT_block, sizeof(FAT_block), 1, outptr);
}
else // byte is 255 but not part of a signature
{
if (outptr != NULL)
{
// move pointer back 4 bytes after checking what they contain
fseek(inptr, signature_offset, SEEK_CUR);
//read FAT block from forensic image into buffer
fread(FAT_block, sizeof(FAT_block), 1, inptr);
// write FAT block buffer to file
fwrite(FAT_block, sizeof(FAT_block), 1, outptr);
}
}
}
else // if byte is not 255
{
if (outptr != NULL)
{
//back up one byte
fseek(inptr, -1, SEEK_CUR);
//read FAT block from forensic image into buffer
fread(FAT_block, sizeof(FAT_block), 1, inptr);
// write FAT block buffer to file
fwrite(FAT_block, sizeof(FAT_block), 1, outptr);
}
}
}
// close files
fclose(inptr);
if (outptr != NULL)
{
fclose(outptr);
}
return 0;
}
// helper functions
int check_args(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "Invalid Input.\nForensic image file must be provided.\n");
return 1;
}
FILE *inptr = fopen(argv[1], "r");
if (inptr == NULL)
{
fprintf(stderr, "File does not exist.\n");
return 2;
}
fclose(inptr);
return 0;
}
bool signature_is_present(BYTE potential_sig[4], SIG jpeg_sig)
{
if( potential_sig[0] == jpeg_sig.byte_1 &&
potential_sig[1] == jpeg_sig.byte_2 &&
potential_sig[2] == jpeg_sig.byte_3 &&
potential_sig[3] >= jpeg_sig.byte_4_min &&
potential_sig[3] <= jpeg_sig.byte_4_max )
{
return true;
}
return false;
}
SIG set_jpeg_signature(void)
{
SIG jpeg_sig;
jpeg_sig.byte_1 = 255;
jpeg_sig.byte_2 = 216;
jpeg_sig.byte_3 = 255;
jpeg_sig.byte_4_min = 224;
jpeg_sig.byte_4_max = 239;
return jpeg_sig;
}

image recovery program has an issue

Well basically I wrote this program for my computer course (shoutout CS50) that recovers images from a .raw file. I have managed to have the program recover 48 of the 50 files in that file.
The issue im having right now with the program is that the program cannot recover both the first and the second file located on .raw. It either reads and writes the very first file (this girl in a snowy background) or the second file on the .raw (guy behind books).
For some reason if I change fopen from write to append I can switch between the photo of the girl and the guy, but I cant seem to be able to open both.
https://github.com/CoreData/cs50/blob/master/pset4/jpg/card.raw
This is the link to card.raw, unfortunately its not the same one that Im using but even using this one you get two different images for image1.jpg depending on whether you have fopen with an "a" or "w".
Any ideas???
if you guys want any additional info just let me know
#include <stdio.h>
#include <stdlib.h>
#include "bmp2.h"
int main(void)
{
/*OPEN CARD FILE*/
char* infile = "card.raw";;
FILE* card = fopen(infile, "r");
if (card == NULL)
{
printf("Could not open %s.\n", "card.raw");
return 2;
}
int f = 0, c = 0, l = 0, x = 128, imageno = 1;
// c signals that a jpg is being written
// l size control, 0 means 0 jpgs
FILE* images;
char* title = (char*)malloc(15);
/*repeat until end of card*/
do
{
//read one block into buffer
INTROJPG *buffer = (INTROJPG*)malloc(sizeof(INTROJPG)*x);
for (int i = 0; i < 128; i++)
{
fread(&buffer[i], sizeof(INTROJPG), 1, card);
}
if (buffer[0].first == 0xff && buffer[0].second == 0xd8 && buffer[0].third == 0xff)
{
sprintf(title, "image%d.jpg", imageno); //change jpg title
if (f == 1) //close previous jpg
{
fclose(images);
imageno++;
}
images = fopen(title, "w");
f = 1; //very first jpg has been opened
c = 1; //jpg open
l++; //jpg count + 1
}
//jpg already open?
if (c == 1)
{
for (int i = 0; i < 128; i++)
{
fwrite(&buffer[i], sizeof(INTROJPG), 1, images);
}
}
free(buffer);
}
while (l < 50);
free(title);
return 5;
//close any remaining files
}
and this is my bmp2.h file
#include <stdint.h>
/**
* Common Data Types
*
* The data types in this section are essentially aliases for C/C++
* primitive data types.
*
* Adapted from http://msdn.microsoft.com/en-us/library/cc230309.aspx.
* See http://en.wikipedia.org/wiki/Stdint.h for more on stdint.h.
*/
typedef uint8_t BYTE;
typedef uint32_t DWORD;
typedef int32_t LONG;
typedef uint16_t WORD;
/**
* BITMAPFILEHEADER
*
* The BITMAPFILEHEADER structure contains information about the type, size,
* and layout of a file that contains a DIB [device-independent bitmap].
*
* Adapted from http://msdn.microsoft.com/en-us/library/dd183374(VS.85).aspx.
*/
typedef struct
{
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} __attribute__((__packed__))
BITMAPFILEHEADER;
/**
* BITMAPINFOHEADER
*
* The BITMAPINFOHEADER structure contains information about the
* dimensions and color format of a DIB [device-independent bitmap].
*
* Adapted from http://msdn.microsoft.com/en-us/library/dd183376(VS.85).aspx.
*/
typedef struct
{
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} __attribute__((__packed__))
BITMAPINFOHEADER;
/**
* RGBTRIPLE
*
* This structure describes a color consisting of relative intensities of
* red, green, and blue.
*
* Adapted from http://msdn.microsoft.com/en-us/library/aa922590.aspx.
*/
typedef struct
{
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;
typedef struct
{
BYTE first;
BYTE second;
BYTE third;
BYTE fourth;
} __attribute__((__packed__))
INTROJPG;
typedef struct
{
BYTE image;
}
BYTEIMAGE;
First things first, I'll try to improve a few things in your code. I've also done this pset and it is nice to help others.
INTROJPG *buffer = (INTROJPG*)malloc(sizeof(INTROJPG)*x);
At this part, you know that the size of both INTROJPG and x are constant, so there is no need to constantly allocate and free memory at every iteration, that takes much more time than simply creating a normal array. Also, why is the buffer a pointer to INTROJPG? If it is only to test for a header at each iteration, I don't think it is worth it, you could simply access the first 4 bytes of a normal BYTE array.
I'd create a static array of 512 BYTEs (the struct on the library), because this is the size you are constantly allocating and freeing and also you are using BYTEs, not INTROJPGs.
Second, at this section and another similar one:
for (int i = 0; i < 128; i++)
{
fread(&buffer[i], sizeof(INTROJPG), 1, card);
}
There is absolutely no need for this loop or, again, even using INTROJPG. You are always reading and writing 512 bytes, you could use:
fread(buffer, 4, 128, card);
// or even better
fread(buffer, 512, 1, card);
Now about your problem, I've tested your code (without any modifications) multiple times and found nothing wrong with image1.jpg and image2.jpg. Yes, I changed "w" mode to "a" and vice-versa.
However, your code is faulty in regard to the last image, your last image is image49.jpg, when it should be image50.jpg, and your image49.jpg does not even open, and that's because the loop is finished before the rest of image49.jpg is stored, i.e., you are storing only the first 512 bytes of image49.jpg.
To fix that, I've changed the condition of the do-while loop to keep going until the end of the card file, IIRC the problem guarantees the last block being part of the last image or something like that, if not, it's up to you to fix this little problem!
#include <stdio.h>
#include <stdlib.h>
#include "bmp2.h"
int main(void)
{
/*OPEN CARD FILE*/
char* infile = "card.raw";;
FILE* card = fopen(infile, "r");
if (card == NULL)
{
printf("Could not open %s.\n", "card.raw");
return 2;
}
int f = 0, c = 0, imageno = 1;
// c signals that a jpg is being written
// l size control, 0 means 0 jpgs
FILE* images;
char title[25];
BYTE buffer[512];
/*repeat until end of card*/
do
{
fread(buffer, 512, 1, card);
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff)
{
sprintf(title, "image%d.jpg", imageno); //change jpg title
if (f == 1) //close previous jpg
{
fclose(images);
imageno++;
}
images = fopen(title, "w");
f = 1; //very first jpg has been opened
c = 1; //jpg open
}
//jpg already open?
if (c == 1) fwrite(buffer, 512, 1, images);
}
while (!feof(card));
return 5;
//close any remaining files
}
One last thing, why are you returning 5 at the end of the program? Just curious.

Writing Bitmap Image to File

I'm trying to read in a bitmap image from one file and write it to another just to check that the contents were transferred. However when I run my code, the image doesn't get created into the output file. Instead, whenever I click on the new file it tells me that the file couldn't be opened. Here is what my header file looks like:
//////////////////////////////////////////////////////////////////////
// RGB.h header file for bitmap BMP definitions
// adapted from <WinGDI.h>
///To get DIB header struct. winGDI.h is huge overkill for the needs here
#ifndef RGBH //don't doubly include this stuff, set a flag when first including
#define RGBH
/* structures for defining DIBs //from WinGDI.h */
typedef unsigned short WORD;
typedef unsigned int DWORD;
typedef unsigned long int LONG;
typedef unsigned char BYTE;
typedef struct tagBITMAPFILEHEADER {
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} BITMAPFILEHEADER, *PBITMAPFILEHEADER;
typedef PBITMAPFILEHEADER pbfh;
typedef struct tagBITMAPINFOHEADER {
DWORD biSize; /* used to get to color table */
DWORD biWidth;
DWORD biHeight;
WORD biPlanes;
WORD biBitCount;
} BITMAPINFOHEADER, *PBITMAPINFOHEADER;
typedef BITMAPINFOHEADER pbih;
typedef struct tagRGBTRIPLE { //from WinGDI.h
BYTE b; //rgbtBlue;
BYTE g; //rgbtGreen;
BYTE r; //rgbtRed;
} pix, *ppix;
#define BYTES_PER_PIX sizeof(pix)
const pix RED = {0,0,255};
const pix GREEN = {0,255,0};
const pix BLUE = {255,0,0};
#endif
////////////////////// End of RGB.h header file ////////////////////////////////
And here is the code I have written:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "RGB.h" //header file for Bitmap
BITMAPFILEHEADER *hp; //var pointer to the header file for bitmap
BITMAPINFOHEADER *p; //var pointer to the info file for bitmap
#define SIZE 100
int main(void)
{
FILE *bp, *op; //var for two file streams
char pix[SIZE]; //var for char name of input file
char out[SIZE]; //var for char name of output file
int n; //var to hold different values through out the program
unsigned char *bitmapImage; //var to store image data
printf("Enter bitmap filename: "); //prompts user to enter filename
scanf("%s", pix); //collects filename from user
//open filename in read binary mode
if((bp = fopen(pix, "rb")) == NULL) if ((bp = fopen(pix, "rb")) == NULL)
{
printf("Can't open file %s", bp); //prints if file path wasn't valid
getchar();
exit (1);
}
//malloc memory for file header
hp = (tagBITMAPFILEHEADER*)malloc(sizeof(tagBITMAPFILEHEADER));
//reads the bitmap file header
n = fread(pix, 1,SIZE, bp);
//read bitmap info header
fread(bp, sizeof(tagBITMAPINFOHEADER), 1, bp);
//allocate enough memory for the bitmap image data
p = (tagBITMAPINFOHEADER*) (pix+14);
bitmapImage = (unsigned char*) malloc(p->biSize);
//verify memory allocation
if (!bitmapImage)
{
free(bitmapImage);
fclose(bp);
puts("Memory allocation not allowed");
return NULL;
}
puts("Input File Statistics: \n");
printf("File size: %ld bytes", p->biSize); //prints out total file size
printf("\nWidth x Height = %ld x %ld", p->biWidth, p->biHeight); //prints out dimensions of image
printf("\nBits/pixel = %u\n", p->biBitCount);
printf("\nEnter an output filename for bitmap: "); //prompts user for output file name
scanf("%s", out); //collects pathway from user
//open output file
if((op = fopen(out, "wb")) == NULL)
{
puts("Invalid file");
fclose(op);
exit (2);
}
fclose(op);
return 0;
}
Any advice would be greatly appreciated! Thanks! O. Helm
Sometimes the solution is too easy to see.
Are you using the same "counter" in both for loops? I think that will not work.
Also, in your fread and fwrite, you are probably reading to and writing from the same place. You need to update the pointer of where you are reading to.
The comment for your first fread says "reads the bitmap file header". I am not sure it is doing that correctly.
Check your second fread. It might have a fatal problem. Are you sure you want to read into bp? Perhaps it will help you if you use more meaningful names for your variables.
Do you need to write BITMAPFILEHEADER and BITMAPINFOHEADER out? Check to ensure you are doing that correctly.
Since this is a class assignment, obviously it is best to not give precise help. I hope this helps enough to make progress. If there is anything more than I hope you can find them by looking closely.

Resources