c语言给bmp图片加水印
时间: 2023-08-04 07:07:17 浏览: 131
C++ bmp图像添加水印
5星 · 资源好评率100%
可以使用C语言的图形处理库来给BMP图片加水印。以下是一个简单的实现示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义BMP文件头结构体
#pragma pack(2)
typedef struct {
unsigned short bfType;
unsigned int bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned int bfOffBits;
} BMPFILEHEADER;
// 定义BMP信息头结构体
#pragma pack(2)
typedef struct {
unsigned int biSize;
int biWidth;
int biHeight;
unsigned short biPlanes;
unsigned short biBitCount;
unsigned int biCompression;
unsigned int biSizeImage;
int biXPelsPerMeter;
int biYPelsPerMeter;
unsigned int biClrUsed;
unsigned int biClrImportant;
} BMPINFOHEADER;
int main() {
// 打开原图文件
FILE *fp = fopen("original.bmp", "rb");
if (fp == NULL) {
printf("Failed to open file.\n");
return -1;
}
// 读取BMP文件头
BMPFILEHEADER fileHeader;
fread(&fileHeader, sizeof(BMPFILEHEADER), 1, fp);
// 读取BMP信息头
BMPINFOHEADER infoHeader;
fread(&infoHeader, sizeof(BMPINFOHEADER), 1, fp);
// 计算像素数据的大小
int width = infoHeader.biWidth;
int height = infoHeader.biHeight;
int rowSize = (width * 3 + 3) / 4 * 4;
int dataSize = rowSize * height;
// 分配内存并读取像素数据
unsigned char *data = (unsigned char *)malloc(dataSize);
fread(data, dataSize, 1, fp);
// 关闭原图文件
fclose(fp);
// 添加水印
char *watermark = "My Watermark";
int watermarkLen = strlen(watermark);
int watermarkWidth = watermarkLen * 8;
int watermarkHeight = 16;
int watermarkX = (width - watermarkWidth) / 2;
int watermarkY = (height - watermarkHeight) / 2;
unsigned char watermarkColor[3] = {255, 255, 255};
int i, j, k;
for (i = 0; i < watermarkHeight; i++) {
for (j = 0; j < watermarkWidth; j++) {
int x = watermarkX + j;
int y = watermarkY + i;
if (x >= 0 && x < width && y >= 0 && y < height) {
int offset = y * rowSize + x * 3;
for (k = 0; k < 3; k++) {
data[offset + k] = (data[offset + k] + watermarkColor[k]) / 2;
}
}
}
}
// 打开输出文件
fp = fopen("watermarked.bmp", "wb");
if (fp == NULL) {
printf("Failed to create file.\n");
return -1;
}
// 写入BMP文件头
fwrite(&fileHeader, sizeof(BMPFILEHEADER), 1, fp);
// 写入BMP信息头
fwrite(&infoHeader, sizeof(BMPINFOHEADER), 1, fp);
// 写入像素数据
fwrite(data, dataSize, 1, fp);
// 关闭输出文件
fclose(fp);
// 释放内存
free(data);
return 0;
}
```
这个程序打开一个名为"original.bmp"的BMP图片文件,向其中心位置添加一个白色的"My Watermark"水印,然后将结果保存为"watermarked.bmp"文件。
阅读全文