C++讀取圖片二進制數據並保存

1、將圖片讀取爲char* 數據

char* pData = NULL;

bool GetTextureData(CString sFilePath,char* &pData)
{
	int nLen = 0;
	FILE* fp = NULL;

	const char* chFileName = sFilePath.AllocANSIString();
	fopen_s(&fp, chFileName, "rb");

	if(!fp)
	{
		delete chFileName;
		chFileName = NULL;

		return false;
	}

	fseek(fp, 0, SEEK_END);
	nLen = ftell(fp);
	fseek(fp, 0, SEEK_SET);

	pData = new char[nLen + 1];

	fread(pData,1,nLen,fp);

	pData[nLen] = '\0';

	fclose(fp);

	delete chFileName;
	chFileName = NULL;

	if (!pData)
	{
		return false;
	}

	return true;
}

或用MFC的CFile

{
	CFile file;
	if (FALSE == file.Open(sFilePath,CFile::modeRead|CFile::typeBinary))
	{
		return false;
	}
	UINT nLen = (UINT)file.GetLength();

	pData = new char[nLen + 1];
	file.Read(pData,nLen);
	pData[nLen] = '\0';
	file.Close();

	if(pData == NULL) return false;

	return true;
}

2、將圖片讀取爲BYTE數組

std::vector<BYTE> fileData;
bool GetTextureFileData(CString strTextPath,std::vector<BYTE>&  fileData))
{
	int nLen = 0;
	FILE* fp = NULL;

	_tfopen_s(&fp, (PCTSTR)sFileName, _T("rb"));

	if(!fp)
	{
		return false;
	}

	fseek(fp, 0, SEEK_END);
	nLen = ftell(fp);
	fseek(fp, 0, SEEK_SET);

	DataBuffer.resize(nLen);

	fread(DataBuffer.data(),1,nLen,fp);

	fclose(fp);

	return true;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章