编程语言
首页 > 编程语言> > c/c++读写png照片

c/c++读写png照片

作者:互联网

seekg()对文件定位,有两个参数:偏移量和基地址。
偏移量:正负数值,正的表示向后偏移,负的表示向前偏移
基地址:表示输入流的位置,3种表示:
ios::beg:开始位置
ios::cur:当前位置
ios::end:结束位置
tellg()函数无参数,返回当前定位指针的位置,也代表着输入流的大小。

#include <fstream> // ifstream, ifstream::in
#include <iostream>
void writePicture(std::string path, char* cContent, int ilength)
{
	FILE* pw;
	pw = std::fopen(path.c_str(), "wb");
	fwrite(cContent, sizeof(char), ilength, pw);
	fflush(pw);
	fclose(pw);
}
void ReadWritePicture(const std::string& szReadPath, const std::string& szWritePath)
{
	// 1. 打开图片
	std::ifstream iPicture(szReadPath, std::ifstream::in | std::ios::binary);
	// 2. 计算图片长度
	iPicture.seekg(0, iPicture.end);    //基地址为结束位置,偏移量为0
	int length = iPicture.tellg();
	iPicture.seekg(0, iPicture.beg);     //基地址为结束位置,偏移量为0
	// 3. 创建内存缓存区
	char* cCache = new char[length];
	// 4. 读取图片到内存中
	iPicture.read(cCache, length);
	iPicture.close();
	writePicture(szWritePath, cCache, length);
	if (nullptr != cCache)
	{
		delete[] cCache;
	}
}
int main() {
	std::string szReadPath = "test.png";
	std::string szWritePath = "image.png";
	ReadWritePicture(szReadPath, szWritePath);
	return 0;
}
#include <fstream> // ifstream, ifstream::in
#include <iostream>

void ReadPicture(const std::string& szReadPath, std::string& szContent, int& ilength)
{
	// 1. 打开图片
	std::ifstream iPicture(szReadPath, std::ifstream::in | std::ios::binary);
	// 2. 计算图片长度
	iPicture.seekg(0, iPicture.end);    //基地址为结束位置,偏移量为0
	ilength = iPicture.tellg();
	iPicture.seekg(0, iPicture.beg);     //基地址为结束位置,偏移量为0
	// 3. 创建内存缓存区
	char* cCache = new char[ilength];
	// 4. 读取图片到内存中
	iPicture.read(cCache, ilength);
	iPicture.close();

	szContent.assign(reinterpret_cast<char*>(&cCache), sizeof(cCache));
	/*if (nullptr != cCache)
	{
		delete[] cCache;
	}*/
}
void writePicture(const std::string& szWritePath, const std::string& szContent, const int& ilength)
{
	FILE* pw;
	pw = std::fopen(szWritePath.c_str(), "wb");
	char* cCache = new char[ilength];
	memcpy(&cCache, szContent.c_str(), sizeof(cCache));
	fwrite(cCache, sizeof(char), ilength, pw);
	fflush(pw);
	fclose(pw);
	if (nullptr != cCache)
	{
		delete[] cCache;
	}
}

int main() {
	std::string szReadPath = "test.png";
	std::string szWritePath = "image.png";
	std::string szContent = "";
	int ilength = 0;
	ReadPicture(szReadPath, szContent, ilength);
	writePicture(szWritePath, szContent, ilength);
	return 0;
}

标签:std,string,读写,c++,cCache,ilength,iPicture,png,pw
来源: https://blog.csdn.net/qq_34552942/article/details/123608150