CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: hrydgard/ppsspp
Path: blob/master/Common/Data/Format/PNGLoad.cpp
Views: 1401
1
#include <cstdio>
2
#include <cstdlib>
3
#include <cstring>
4
#include <png.h>
5
6
#include "Common/Data/Format/PNGLoad.h"
7
#include "Common/Log.h"
8
9
// *image_data_ptr should be deleted with free()
10
// return value of 1 == success.
11
int pngLoad(const char *file, int *pwidth, int *pheight, unsigned char **image_data_ptr) {
12
png_image png;
13
memset(&png, 0, sizeof(png));
14
png.version = PNG_IMAGE_VERSION;
15
16
png_image_begin_read_from_file(&png, file);
17
18
if (PNG_IMAGE_FAILED(png))
19
{
20
WARN_LOG(Log::IO, "pngLoad: %s (%s)", png.message, file);
21
*image_data_ptr = nullptr;
22
return 0;
23
}
24
*pwidth = png.width;
25
*pheight = png.height;
26
png.format = PNG_FORMAT_RGBA;
27
28
int stride = PNG_IMAGE_ROW_STRIDE(png);
29
*image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png));
30
png_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL);
31
return 1;
32
}
33
34
int pngLoadPtr(const unsigned char *input_ptr, size_t input_len, int *pwidth, int *pheight, unsigned char **image_data_ptr) {
35
png_image png{};
36
png.version = PNG_IMAGE_VERSION;
37
38
png_image_begin_read_from_memory(&png, input_ptr, input_len);
39
40
if (PNG_IMAGE_FAILED(png)) {
41
WARN_LOG(Log::IO, "pngLoad: %s", png.message);
42
*image_data_ptr = nullptr;
43
return 0;
44
}
45
*pwidth = png.width;
46
*pheight = png.height;
47
png.format = PNG_FORMAT_RGBA;
48
49
int stride = PNG_IMAGE_ROW_STRIDE(png);
50
51
size_t size = PNG_IMAGE_SIZE(png);
52
if (!size) {
53
ERROR_LOG(Log::IO, "pngLoad: empty image");
54
*image_data_ptr = nullptr;
55
return 0;
56
}
57
58
*image_data_ptr = (unsigned char *)malloc(size);
59
png_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL);
60
return 1;
61
}
62
63
bool PNGHeaderPeek::IsValidPNGHeader() const {
64
if (magic != 0x474e5089 || ihdrTag != 0x52444849) {
65
return false;
66
}
67
// Reject crazy sized images, too.
68
if (Width() > 32768 && Height() > 32768) {
69
return false;
70
}
71
return true;
72
}
73
74