Esempio n. 1
0
File: bmp.c Progetto: jyshi/ece264
/* The input argument is the source file pointer. 
 * The function returns an address to a dynamically allocated BMP_Image only 
 * if the file * contains a valid image file 
 * Otherwise, return NULL
 * If the function cannot get the necessary memory to store the image, also 
 * return NULL
 * Any error messages should be printed to stderr
 */
BMP_Image *Read_BMP_Image(FILE* fptr) {
  
   BMP_Image *bmp_image = NULL;
   int n;
  //Allocate memory for BMP_Image*;
	
	
    bmp_image = (BMP_Image *)malloc(sizeof(BMP_Image));
	if(bmp_image == NULL)
   	{
		fprintf(stderr, "Error allocating memory\n");
	    return NULL;
	}

  //Read the first 54 bytes of the source into the header
    n = fread(&(bmp_image->header), sizeof(BMP_Header), 1, fptr);
	// if read successful, check validity of header
	if(n != 1)
	{
		fprintf(stderr, "Error reading input file\n");
		return NULL;
	}
	if(!(Is_BMP_Header_Valid(&(bmp_image->header), fptr)))
	{
		fprintf(stderr, "Input file not in expected format\n");
		return NULL;
	}
  // Allocate memory for image data
	fseek(fptr, sizeof(BMP_Header), SEEK_SET);
	bmp_image->data = (unsigned char*)malloc((bmp_image->header).imagesize * sizeof(unsigned char));	
	if(bmp_image->data == NULL)
	{
		fprintf(stderr, "Error allocating memory\n");
		return NULL;
	}
 
  // read in the image data
	n = fread(bmp_image->data, sizeof(unsigned char), (bmp_image->header).imagesize, fptr);
	if(n != (bmp_image->header).imagesize)
	{
		fprintf(stderr, "Error reading input file\n");
		return NULL;
	}
  return bmp_image;
}
Esempio n. 2
0
BMP_Image *Read_BMP_Image(FILE* fptr) {

  // go to the beginning of the file
   BMP_Image *bmp_image = NULL;
   fseek(fptr, 0, SEEK_SET);

  //Allocate memory for BMP_Image*;
   bmp_image = malloc(sizeof(*bmp_image));
   if(bmp_image == NULL){
      return NULL;
   }
  //Read the first 54 bytes of the source into the header
   int status = fread(&(bmp_image -> header), 54, 1, fptr);
   if(status != 1){
      free(bmp_image);
      return NULL;
   }

  // if read successful, check validity of header
   if(!Is_BMP_Header_Valid(&(bmp_image -> header), fptr)){
      free(bmp_image);
      return NULL;
   }

  // Allocate memory for image data
   bmp_image -> data = malloc(bmp_image -> header.imagesize); 
   if(bmp_image -> data == NULL){
      free(bmp_image);
      return NULL;
   }
 
  // read in the image data
   fseek(fptr, 54, SEEK_SET);
   status = fread(bmp_image -> data, bmp_image -> header.imagesize, 1, fptr);
   if(status != 1){
      free(bmp_image -> data);
      free(bmp_image);
      return NULL;
   }

  return bmp_image;
}