【C++】保存网络获取的图片至本地

来源:互联网 发布:家居装饰设计软件 编辑:程序博客网 时间:2024/05/26 09:57

前言


从网络上获取了图片数据之后,如何保存到本地的问题?

本篇是上一篇《【C++】GET、POST网络请求boost.asio实现》的姊妹篇。

无论是GET还是POST,获取的数据均以std::string类型返回,若是图片怎么办?

其实代码写出来很简单,实现方式如下:


博文首发:http://blog.csdn.net/duzixi


源代码


ImgWriter.h

////  ImgWriter.h////  Created by duzixi.com on 15/8/27.//#include <stdio.h>#include <iostream>#include <fstream>using namespace std;// 指定本地路径,保存文件void WriteImgLocal(const char* path, string imgStr);

ImgWriter.cpp

////  ImgWriter.cpp////  Created by duzixi.com on 15/8/27.//#include "ImgWriter.h"using namespace std;// 指定本地路径,保存文件void WriteImgLocal(const char* path, string imgStr){    long size = imgStr.length();        // 1. 定义保存图片的文件    FILE *ofile = fopen(path, "wb");        // 2. 再将string类型转换为char数组    char* imgCharArray = new char[size];    for(int i = 0; i <= size; i++){        imgCharArray[i] = imgStr[i];    }        // 3. 最后将char数组输出保存为图片文件    fwrite(imgCharArray, sizeof(char), size, ofile);        fclose(ofile); // 关闭文件}


后语


在这个例子里,保存图像文件时需要将string类型转换为char数组是核心关键。

换了新工作之后,没想到会这么快就介入C++的内容。

看似基本简单的功能,若是不熟悉鼓弄起来真是花费好久。

看到很多本质层面的东西,视野也透亮了很多。

0 0