2016-12-27 08:32:32 -07:00
|
|
|
// Copyright 2016 Dolphin Emulator Project
|
|
|
|
// Licensed under GPLv2+
|
|
|
|
// Refer to the license.txt file included.
|
|
|
|
|
|
|
|
#include "Common/Image.h"
|
|
|
|
|
2020-11-25 20:34:51 -07:00
|
|
|
#include <string>
|
2016-12-27 08:32:32 -07:00
|
|
|
#include <vector>
|
|
|
|
|
2018-08-18 07:37:20 -06:00
|
|
|
#include <png.h>
|
|
|
|
|
2016-12-27 08:32:32 -07:00
|
|
|
#include "Common/CommonTypes.h"
|
|
|
|
|
|
|
|
namespace Common
|
|
|
|
{
|
|
|
|
bool LoadPNG(const std::vector<u8>& input, std::vector<u8>* data_out, u32* width_out,
|
|
|
|
u32* height_out)
|
|
|
|
{
|
2018-08-18 07:37:20 -06:00
|
|
|
// Using the 'Simplified API' of libpng; see section V in the libpng manual.
|
2016-12-27 08:32:32 -07:00
|
|
|
|
2018-08-18 07:37:20 -06:00
|
|
|
// Read header
|
|
|
|
png_image png = {};
|
|
|
|
png.version = PNG_IMAGE_VERSION;
|
|
|
|
if (!png_image_begin_read_from_memory(&png, input.data(), input.size()))
|
2016-12-27 08:32:32 -07:00
|
|
|
return false;
|
|
|
|
|
2018-08-18 07:37:20 -06:00
|
|
|
// Prepare output vector
|
2018-08-19 09:35:15 -06:00
|
|
|
png.format = PNG_FORMAT_RGBA;
|
2018-08-18 07:37:20 -06:00
|
|
|
size_t png_size = PNG_IMAGE_SIZE(png);
|
|
|
|
data_out->resize(png_size);
|
2016-12-27 08:32:32 -07:00
|
|
|
|
2018-08-18 07:37:20 -06:00
|
|
|
// Convert to RGBA and write into output vector
|
|
|
|
if (!png_image_finish_read(&png, nullptr, data_out->data(), 0, nullptr))
|
2016-12-27 08:32:32 -07:00
|
|
|
return false;
|
|
|
|
|
2018-08-18 07:37:20 -06:00
|
|
|
*width_out = png.width;
|
|
|
|
*height_out = png.height;
|
2016-12-27 08:32:32 -07:00
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
2020-11-25 20:34:51 -07:00
|
|
|
|
|
|
|
bool SavePNG(const std::string& path, const u8* input, ImageByteFormat format, u32 width,
|
|
|
|
u32 height, int stride)
|
|
|
|
{
|
|
|
|
png_image png = {};
|
|
|
|
png.version = PNG_IMAGE_VERSION;
|
|
|
|
png.width = width;
|
|
|
|
png.height = height;
|
|
|
|
|
|
|
|
switch (format)
|
|
|
|
{
|
|
|
|
case ImageByteFormat::RGB:
|
|
|
|
png.format = PNG_FORMAT_RGB;
|
|
|
|
break;
|
|
|
|
case ImageByteFormat::RGBA:
|
|
|
|
png.format = PNG_FORMAT_RGBA;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
png_image_write_to_file(&png, path.c_str(), 0, input, stride, nullptr);
|
|
|
|
if (png.warning_or_error & PNG_IMAGE_ERROR)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
2016-12-27 08:32:32 -07:00
|
|
|
} // namespace Common
|