//如果是Windows的话,调用系统API ShellExecuteA打开图片
#if defined(_MSC_VER)
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#define USE_SHELL_OPEN
#endif
#define STB_IMAGE_STATIC
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
//ref:https://github.com/nothings/stb/blob/master/stb_image.h
#define TJE_IMPLEMENTATION
#include "tiny_jpeg.h"
//ref:https://github.com/serge-rgb/TinyJPEG/blob/master/tiny_jpeg.h
#include <math.h>
#include <io.h>
#include <iostream>
#include <string>
#include <chrono>
//计时
auto const epoch = std::chrono::steady_clock::now();
static double now()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - epoch).count() / 1000.0;
};
template <typename FN>
static double bench(const FN &fn)
{
auto took = -now();
return (fn(), took + now());
}
//存储当前传入文件位置的变量
std::string m_curFilePath;
//加载图片
void loadImage(const char *filename, unsigned char *&Output, int &Width, int &Height, int &Channels)
{
Output = stbi_load(filename, &Width, &Height, &Channels, 0);
}
//保存图片
void saveImage(const char *filename, int Width, int Height, int Channels, unsigned char *Output, bool open = true)
{
std::string saveFile = m_curFilePath;
saveFile += filename;
//保存为jpg
if (!tje_encode_to_file(saveFile.c_str(), Width, Height, Channels, Output))
{
fprintf(stderr, "写入 JPEG 文件失败.\n");
return;
}
#ifdef USE_SHELL_OPEN
if (open)
ShellExecuteA(NULL, "open", saveFile.c_str(), NULL, NULL, SW_SHOW);
#else
//其他平台暂不实现
#endif
}
//取当前传入的文件位置
void getCurrentFilePath(const char *filePath, std::string &curFilePath)
{
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
curFilePath.clear();
_splitpath_s(filePath, drive, dir, fname, ext);
curFilePath += drive;
curFilePath += dir;
curFilePath += fname;
curFilePath += "_";
}
//算法处理,这里以一个反色作为例子
void processImage(unsigned char *Input, unsigned char *Output, unsigned int Width, unsigned int Height, unsigned int Channels)
{
int Stride = Width * Channels;
if (Channels == 1)
{
for (unsigned int Y = 0; Y < Height; Y++)
{
unsigned char *scanLineOut = Output + (Y * Stride);
unsigned char *scanLineIn = Input + (Y * Stride);
for (unsigned int X = 0; X < Width; X++)
{
scanLineOut[0] = 255 - scanLineIn[0];
scanLineIn++;
scanLineOut++;
}
}
}
else if (Channels == 3 || Channels == 4)
{
for (unsigned int Y = 0; Y < Height; Y++)
{
unsigned char *scanLineOut = Output + (Y * Stride);
unsigned char *scanLineIn = Input + (Y * Stride);
for (unsigned int X = 0; X < Width; X++)
{
scanLineOut[0] = 255 - scanLineIn[0];
scanLineOut[1] = 255 - scanLineIn[1];
scanLineOut[2] = 255 - scanLineIn[2];
//通道数为4时,不处理A通道反色(scanLineOut[3] = 255- scanLineIn[3];
scanLineIn += Channels;
scanLineOut += Channels;
}
}
}
}
int main(int argc, char **argv)
{
std::cout << "Image Processing " &l