C++ 二进制方式读取和存储图片文件

#include "stdafx.h"
#include <map>
#include <string>
#include <ctime>
#include <sstream>
#include <iomanip>
#include <direct.h>
#include <chrono>
 
int main(){
	FILE* fp;
	// 1. 二进制打开图片文件
	ifstream is("D:/workplace/test.jpg", ifstream::in | ios::binary);
	// 2. 计算图片长度
	is.seekg(0, is.end);
	int length = is.tellg();
	is.seekg(0, is.beg);
	// 3. 创建内存缓存区
	char * buffer = new char[length];
	// 4. 读取图片,放入缓存
	is.read(buffer, length);
    if (length>0)
	// 到此,图片已经成功的被读取到内存(buffer)中
	//以二进制写入方式
    std::string file_name;
	std::string strPicId;
	GetUUID(strPicId);
	file_name.append(strPicId);
	file_name.append(".jpg");
	std::int64_t curTime = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count() / 1000;
	struct tm *t;
	t = localtime(&curTime);
	std::string file_path;
	CConfigCenter::GetInstance().GetTomcatJpgUrl(file_path);
	std::string pic;
	char cFolderName[128] = { 0 };
	char cTime[64] = { 0 };
	sprintf(cFolderName, "%s/%d%02d%02d/", file_path.c_str(), t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
	sprintf(cTime, "%d%02d%02d/", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
	std::string strFolder = cFolderName;
	strFolder.append(file_name);
	FILE* fd = fopen(strFolder.c_str(), "wb+");
	std::string strT = cTime;
    if (fd != NULL)
		{
			std::string url;
			CConfigCenter::GetInstance().GetWebPicUrl(url);
			pic.append(url);
			pic.append(strT);
			pic.append(file_name);
			LOG4CPLUS_INFO(LOGGERTAG, "读取图片大小:" << dwBufSize);
			LOG4CPLUS_INFO(LOGGERTAG, "读取图片url:" << pic);
			//从buffer中写数据到fp指向的文件中
	        fwrite(buffer, length, 1, fp);
	        //关闭文件指针,释放buffer内存
            fclose(fp);
	        delete [] buffer;
	        is.close();
		}
	return 0;
}
 
 

fwrite函数就是写文件的函数,它的函数原型如下:
fwrite(const void *buffer, size_t  size,  size_t count , FILE *stream)

可以看到这个函数的参数有四个:

buffer : 数据存储的地址

size : 要读取的字节的大小

count : 要读取多少个size大小

stream : 等待被读取的数据源,它是一个指向FILE结构的文件指针

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值