提供32位BMP图像旋转90度的c++代码
时间: 2023-11-04 08:31:48 浏览: 59
以下是C代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
// Open file for reading and writing
FILE *fp = fopen(argv[1], "r+b");
// Read the BMP header
unsigned char header[54];
fread(header, sizeof(unsigned char), 54, fp);
// Extract image width and height from BMP header
int width = *(int*)&header[18];
int height = *(int*)&header[22];
// Calculate padding for each row (if necessary)
int padding = 0;
if ((width * 3) % 4 != 0) {
padding = 4 - (width * 3) % 4;
}
// Allocate memory for image
unsigned char* image = (unsigned char*) malloc(sizeof(unsigned char) * width * height * 3);
// Read image data from the file
fread(image, sizeof(unsigned char), width * height * 3, fp);
// Rotate the image
unsigned char* rotatedImage = (unsigned char*) malloc(sizeof(unsigned char) * width * height * 3);
int newWidth = height;
int newHeight = width;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int oldIndex = (y * width + x) * 3;
int newIndex = ((newWidth - x - 1) * newWidth + y) * 3;
rotatedImage[newIndex + 0] = image[oldIndex + 0];
rotatedImage[newIndex + 1] = image[oldIndex + 1];
rotatedImage[newIndex + 2] = image[oldIndex + 2];
}
// Add padding bytes (if necessary)
for (int i = 0; i < padding; i++) {
fputc(0x00, fp);
}
}
// Write the rotated image to a new file
char* outFileName = "rotated.bmp";
FILE *out = fopen(outFileName, "wb");
fwrite(header, sizeof(unsigned char), 54, out);
fwrite(rotatedImage, sizeof(unsigned char), newWidth * newHeight * 3, out);
fclose(out);
// Clean up
free(image);
free(rotatedImage);
fclose(fp);
return 0;
}
阅读全文