C++ pgm转jpg格式 网页显示图片
程序员文章站
2022-03-19 23:33:15
...
参考https://mp.csdn.net/postedit/91562301
#include <iostream>
#include <fstream>
#include "jpegenc.h"
#include <cstdio>
int main()
{
FILE* fp;
std::ifstream pgmfile;
std::string path = "map.pgm";
pgmfile.open(path,std::ios::binary);
std::string line;
int width,height;
getline(pgmfile,line); //获取pgm文件的类型 P2 或者 P5
std::cout << "type is "<<line << std::endl;
line.clear();
getline(pgmfile,line); //获取宽度
width = std::stoi(line);
std::cout << "width is "<<line << std::endl;
line.clear();
getline(pgmfile,line); //获取高度
height = std::stoi(line);
std::cout << "height is "<<line << std::endl;
line.clear();
getline(pgmfile,line); //获取灰度最大值
std::cout << "grayMax is "<<line << std::endl;
line.clear();
getline(pgmfile,line); //获取数据
std::cout << "data is "<<line << std::endl;
struct JPEG_Enc *jpeg_enc;
jpeg_enc = new_jpegenc(width, height, 3);
if(jpeg_enc == NULL) {
return;
}
jpegenc_compress(jpeg_enc, (unsigned char*)line.c_str(), 60, 1);
unsigned char *p = (unsigned char *)malloc(576*608 *sizeof(char));
p = jpegenc_get_enc_buf(jpeg_enc);//如果想程序中直接转换base64则把这一项进行base64转换
printf("%s\n",p);
fp = fopen("test.jpg", "wb");
if (fp == NULL) {
fprintf(stderr, "Could not open file for writing\n");
return;
}
fwrite(jpegenc_get_enc_buf(jpeg_enc), 1, jpegenc_get_enc_size(jpeg_enc), fp);
dispose_jpegenc(jpeg_enc);
return 0;
}
编译 链接 -std=c++11 -ljpeg
生成的jpg文件,转换base64
base64 test.jpg
创建1.html 将生成的数据粘贴到下面位置
<!DOCTYPE html>
<html>
<head>
<title>index.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<!--
data表示取得数据的协定名称,image/png是数据类型名称,base64 是数据的编码方法,
逗号后面是image/png文件base64编码后的数据.
data:text/css;base64,base64编码的CSS代码
data:text/javascript,Javascript代码
data:text/javascript;base64,base64编码的Javascript代码
data:image/gif;base64,base64编码的gif图片数据
data:image/png;base64,base64编码的png图片数据
data:image/jpeg;base64,base64编码的jpeg图片数据
data:image/x-icon;base64,base64编码的icon图片数据
-->
<img src="test.png"/>
<img src="data:image/png;base64,粘贴到这里"/>
</body>
</html>
然后打开该html文件