【opencv】图片文件读写

本文展示了两个C++程序片段,分别使用`ifstream`处理图片文件,包括打开、计算长度、创建内存缓存区并进行读取和写入操作。
摘要由CSDN通过智能技术生成
#include <fstream> // ifstream, ifstream::in
using namespace std;

int main(){
	// 1. 打开图片文件
	// 评论区的 @霍鑫网络 帮忙发现一个隐藏的bug,在此表示感谢,已经修正
	ifstream is("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);
	// 到此,图片已经成功的被读取到内存(buffer)中
    //https://www.coder.work/article/1711506
    //https://stackoverrun.com/cn/q/8220469
	delete [] buffer;
	return 0;
}


#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <io.h>
 
using namespace std;
 
int _tmain(int argc, _TCHAR* argv[])
{
	string strpath = "D:\\Dtest5\\Readjpg\\1.jpg";
	string strR1 = "D:\\Dtest5\\Readjpg\\10.jpg";
 
	std::ifstream fin(strpath.c_str(), std::ios::binary);
	fin.seekg(0, ios::end);
	int iSize = fin.tellg();
	char* szBuf = new (std::nothrow) char[iSize];
 
	fin.seekg(0, ios::beg);
	fin.read(szBuf, sizeof(char) * iSize);
	fin.close();
 
	std::ofstream fout(strR1.c_str(), std::ios::binary);
	fout.write(szBuf, sizeof(char) * iSize);
	fout.close();
 
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值