ImageTIF.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "EditorDefs.h"
  9. #include "ImageTIF.h"
  10. /// libTiff
  11. #include <tiffio.h> // TIFF library
  12. // Function prototypes
  13. static tsize_t libtiffDummyReadProc (thandle_t fd, tdata_t buf, tsize_t size);
  14. static tsize_t libtiffDummyWriteProc (thandle_t fd, tdata_t buf, tsize_t size);
  15. static toff_t libtiffDummySizeProc(thandle_t fd);
  16. static toff_t libtiffDummySeekProc (thandle_t fd, toff_t off, int i);
  17. //static int libtiffDummyCloseProc (thandle_t fd);
  18. // Structure used to pass state to our in-memory TIFF file callbacks
  19. struct MemImage
  20. {
  21. uint8 *buffer;
  22. uint32 offset;
  23. uint32 size;
  24. };
  25. /////////////////// Callbacks to libtiff
  26. static int libtiffDummyMapFileProc(thandle_t, tdata_t*, toff_t*)
  27. {
  28. return 0;
  29. }
  30. static void libtiffDummyUnmapFileProc(thandle_t, tdata_t, toff_t)
  31. {
  32. }
  33. static toff_t libtiffDummySizeProc(thandle_t fd)
  34. {
  35. MemImage *memImage = static_cast<MemImage *>(fd);
  36. return memImage->size;
  37. }
  38. static tsize_t
  39. libtiffDummyReadProc (thandle_t fd, tdata_t buf, tsize_t size)
  40. {
  41. MemImage *memImage = static_cast<MemImage *>(fd);
  42. tsize_t nBytesLeft = memImage->size - memImage->offset;
  43. if (size > nBytesLeft)
  44. {
  45. size = nBytesLeft;
  46. }
  47. memcpy(buf, &memImage->buffer[memImage->offset], size);
  48. memImage->offset += static_cast<uint32>(size);
  49. // Return the amount of data read
  50. return size;
  51. }
  52. static tsize_t
  53. libtiffDummyWriteProc ([[maybe_unused]] thandle_t fd, [[maybe_unused]] tdata_t buf, tsize_t size)
  54. {
  55. return (size);
  56. }
  57. static toff_t
  58. libtiffDummySeekProc (thandle_t fd, toff_t off, int i)
  59. {
  60. MemImage *memImage = static_cast<MemImage *>(fd);
  61. switch (i)
  62. {
  63. case SEEK_SET:
  64. memImage->offset = static_cast<uint32>(off);
  65. break;
  66. case SEEK_CUR:
  67. memImage->offset += static_cast<uint32>(off);
  68. break;
  69. case SEEK_END:
  70. memImage->offset = static_cast<uint32>(memImage->size - off);
  71. break;
  72. default:
  73. memImage->offset = static_cast<uint32>(off);
  74. break;
  75. }
  76. // This appears to return the location that it went to
  77. return memImage->offset;
  78. }
  79. static int
  80. libtiffDummyCloseProc ([[maybe_unused]] thandle_t fd)
  81. {
  82. // Return a zero meaning all is well
  83. return 0;
  84. }
  85. bool CImageTIF::Load(const QString& fileName, CImageEx& outImage)
  86. {
  87. CCryFile file;
  88. if (!file.Open(fileName.toUtf8().data(), "rb"))
  89. {
  90. CLogFile::FormatLine("File not found %s", fileName.toUtf8().data());
  91. return false;
  92. }
  93. MemImage memImage;
  94. std::vector<uint8> data;
  95. memImage.size = static_cast<uint32>(file.GetLength());
  96. data.resize(memImage.size);
  97. memImage.buffer = &data[0];
  98. memImage.offset = 0;
  99. file.ReadRaw(memImage.buffer, memImage.size);
  100. // Open the dummy document (which actually only exists in memory)
  101. TIFF* tif = TIFFClientOpen (fileName.toUtf8().data(), "rm", (thandle_t)&memImage, libtiffDummyReadProc,
  102. libtiffDummyWriteProc, libtiffDummySeekProc,
  103. libtiffDummyCloseProc, libtiffDummySizeProc, libtiffDummyMapFileProc, libtiffDummyUnmapFileProc);
  104. // TIFF* tif = TIFFOpen(fileName,"r");
  105. bool bRet = false;
  106. if (tif)
  107. {
  108. uint32 dwWidth, dwHeight;
  109. size_t npixels;
  110. uint32* raster;
  111. char* dccfilename = nullptr;
  112. TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &dwWidth);
  113. TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &dwHeight);
  114. TIFFGetField(tif, TIFFTAG_IMAGEDESCRIPTION, &dccfilename);
  115. npixels = dwWidth * dwHeight;
  116. raster = (uint32*)_TIFFmalloc((tsize_t)(npixels * sizeof(uint32)));
  117. if (raster)
  118. {
  119. if (TIFFReadRGBAImage(tif, dwWidth, dwHeight, raster, 0))
  120. {
  121. if (outImage.Allocate(dwWidth, dwHeight))
  122. {
  123. char* dest = (char*)outImage.GetData();
  124. uint32 dwPitch = dwWidth * 4;
  125. for (uint32 dwY = 0; dwY < dwHeight; ++dwY)
  126. {
  127. char* src2 = (char*)&raster[(dwHeight - 1 - dwY) * dwWidth];
  128. char* dest2 = &dest[dwPitch * dwY];
  129. memcpy(dest2, src2, dwWidth * 4);
  130. }
  131. if (dccfilename)
  132. {
  133. outImage.SetDccFilename(dccfilename);
  134. }
  135. bRet = true;
  136. }
  137. }
  138. _TIFFfree(raster);
  139. }
  140. TIFFClose(tif);
  141. }
  142. if (!bRet)
  143. {
  144. outImage.Detach();
  145. }
  146. return bRet;
  147. }
  148. bool CImageTIF::Load(const QString& fileName, CFloatImage& outImage)
  149. {
  150. // Defined in GeoTIFF format - http://web.archive.org/web/20160403164508/http://www.remotesensing.org/geotiff/spec/geotiffhome.html
  151. // Used to get the X, Y, Z scales from a GeoTIFF file
  152. static const int GEOTIFF_MODELPIXELSCALE_TAG = 33550;
  153. CCryFile file;
  154. if (!file.Open(fileName.toUtf8().data(), "rb"))
  155. {
  156. CLogFile::FormatLine("File not found %s", fileName.toUtf8().data());
  157. return false;
  158. }
  159. MemImage memImage;
  160. std::vector<uint8> data;
  161. memImage.size = static_cast<int>(file.GetLength());
  162. data.resize(memImage.size);
  163. memImage.buffer = &data[0];
  164. memImage.offset = 0;
  165. file.ReadRaw(memImage.buffer, memImage.size);
  166. // Open the dummy document (which actually only exists in memory)
  167. TIFF* tif = TIFFClientOpen(fileName.toUtf8().data(), "rm", (thandle_t)&memImage, libtiffDummyReadProc,
  168. libtiffDummyWriteProc, libtiffDummySeekProc,
  169. libtiffDummyCloseProc, libtiffDummySizeProc, libtiffDummyMapFileProc, libtiffDummyUnmapFileProc);
  170. // TIFF* tif = TIFFOpen(fileName,"r");
  171. bool bRet = false;
  172. if (tif)
  173. {
  174. uint32 width = 0, height = 0;
  175. uint16 spp = 0, bpp = 0, format = 0;
  176. char* dccfilename = nullptr;
  177. TIFFGetField(tif, TIFFTAG_IMAGEDESCRIPTION, &dccfilename);
  178. TIFFGetFieldDefaulted(tif, TIFFTAG_IMAGEWIDTH, &width);
  179. TIFFGetFieldDefaulted(tif, TIFFTAG_IMAGELENGTH, &height);
  180. TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bpp); // how many bits each color component is. typically 8-bit, but could be 16-bit.
  181. TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &spp); // how many color components per pixel? 1=greyscale, 3=RGB, 4=RGBA
  182. TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLEFORMAT, &format); // format of the pixel data - int, uint, float.
  183. // There are two types of 32-bit floating point TIF semantics. Paint programs tend to use values in the 0.0 - 1.0 range.
  184. // GeoTIFF files use values where 1.0 = 1 meter by default, but also have an optional ZScale parameter to provide additional
  185. // scaling control.
  186. // By default, we'll assume this is a regular TIFF that we want to leave in the 0.0 - 1.0 range.
  187. float pixelValueScale = 1.0f;
  188. // Check to see if it's a GeoTIFF, and if so, whether or not it has the ZScale parameter.
  189. uint32 tagCount = 0;
  190. double *pixelScales = nullptr;
  191. if (TIFFGetField(tif, GEOTIFF_MODELPIXELSCALE_TAG, &tagCount, &pixelScales) == 1)
  192. {
  193. // if there's an xyz scale, and the Z scale isn't 0, let's use it.
  194. if ((tagCount == 3) && (pixelScales != nullptr) && (pixelScales[2] != 0.0f))
  195. {
  196. pixelValueScale = static_cast<float>(pixelScales[2]);
  197. }
  198. }
  199. uint32 linesize = static_cast<uint32>(TIFFScanlineSize(tif));
  200. uint8* linebuf = static_cast<uint8*>(_TIFFmalloc(linesize));
  201. // We assume that a scanline has all of the samples in it. Validate the assumption.
  202. assert(linesize == (width * (bpp / 8) * spp));
  203. // Aliases for linebuf to make it easier to pull different types out of the scanline.
  204. uint16* linebufUint16 = reinterpret_cast<uint16*>(linebuf);
  205. uint32* linebufUint32 = reinterpret_cast<uint32*>(linebuf);
  206. float* linebufFloat = reinterpret_cast<float*>(linebuf);
  207. if (linebuf)
  208. {
  209. if (outImage.Allocate(width, height))
  210. {
  211. float* dest = outImage.GetData();
  212. bRet = true;
  213. float maxPixelValue = 0.0f;
  214. for (uint32 y = 0; y < height; y++)
  215. {
  216. TIFFReadScanline(tif, linebuf, y);
  217. // For each pixel, we either scale or clamp the values to a 16-bit range. It is asymmetric behaviour, but based
  218. // on assumptions about the input data:
  219. // 8-bit values are scaled up because 8-bit textures used as heightmaps are usually scaled-down 16-bit values.
  220. // 32-bit values may or may not need to scale down, depending on the intended authoring range. Our assumption
  221. // is that they were most likely authored with the intent of 1:1 value translations.
  222. for (uint32 x = 0; x < width; x++)
  223. {
  224. switch (bpp)
  225. {
  226. case 8:
  227. // Scale 0-255 to 0.0 - 1.0
  228. dest[(y * width) + x] = static_cast<float>(linebuf[x * spp]) / static_cast<float>(std::numeric_limits<uint8>::max());
  229. break;
  230. case 16:
  231. // Scale 0-65535 to 0.0 - 1.0
  232. dest[(y * width) + x] = static_cast<float>(linebufUint16[x * spp]) / static_cast<float>(std::numeric_limits<uint16>::max());
  233. break;
  234. case 32:
  235. // 32-bit values could be ints or floats.
  236. if (format == SAMPLEFORMAT_INT)
  237. {
  238. // Scale 0-max int32 to 0.0 - 1.0
  239. dest[(y * width) + x] = clamp_tpl(static_cast<float>(linebufUint32[x * spp]) / static_cast<float>(std::numeric_limits<int32>::max()), 0.0f, 1.0f);
  240. }
  241. else if (format == SAMPLEFORMAT_UINT)
  242. {
  243. // Scale 0-max uint32 to 0.0 - 1.0
  244. dest[(y * width) + x] = clamp_tpl(static_cast<float>(linebufUint32[x * spp]) / static_cast<float>(std::numeric_limits<uint32>::max()), 0.0f, 1.0f);
  245. }
  246. else if (format == SAMPLEFORMAT_IEEEFP)
  247. {
  248. dest[(y * width) + x] = linebufFloat[x * spp] * pixelValueScale;
  249. }
  250. else
  251. {
  252. // Unknown / unsupported format.
  253. bRet = false;
  254. }
  255. break;
  256. default:
  257. // Unknown / unsupported format.
  258. bRet = false;
  259. break;
  260. }
  261. maxPixelValue = max(maxPixelValue, dest[(y * width) + x]);
  262. }
  263. }
  264. if (dccfilename)
  265. {
  266. outImage.SetDccFilename(dccfilename);
  267. }
  268. // If this is a GeoTIFF using 32-bit floats, we will end up outside the 0.0 - 1.0 range. Let's scale it back down to 0.0 - 1.0.
  269. if (maxPixelValue > 1.0f)
  270. {
  271. for (uint32 y = 0; y < height; y++)
  272. {
  273. for (uint32 x = 0; x < width; x++)
  274. {
  275. dest[(y * width) + x] = dest[(y * width) + x] / maxPixelValue;
  276. }
  277. }
  278. }
  279. }
  280. _TIFFfree(linebuf);
  281. }
  282. TIFFClose(tif);
  283. }
  284. if (!bRet)
  285. {
  286. outImage.Detach();
  287. }
  288. return bRet;
  289. }
  290. //////////////////////////////////////////////////////////////////////////
  291. bool CImageTIF::SaveRAW(const QString& fileName, const void* pData, int width, int height, int bytesPerChannel, int numChannels, bool bFloat, const char* preset)
  292. {
  293. if (bFloat && (bytesPerChannel != 2 && bytesPerChannel != 4))
  294. {
  295. bFloat = false;
  296. }
  297. bool bRet = false;
  298. CFileUtil::OverwriteFile(fileName);
  299. TIFF* tif = TIFFOpen(fileName.toUtf8().data(), "wb");
  300. if (tif)
  301. {
  302. TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
  303. TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
  304. TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, numChannels);
  305. TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bytesPerChannel * 8);
  306. TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  307. TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
  308. TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
  309. TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, (numChannels == 1) ? PHOTOMETRIC_MINISBLACK : PHOTOMETRIC_RGB);
  310. TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
  311. if (bFloat)
  312. {
  313. TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
  314. }
  315. if (preset && preset[0])
  316. {
  317. AZStd::string tiffphotoshopdata, valueheader;
  318. AZStd::string presetkeyvalue = AZStd::string("/preset=") + AZStd::string(preset);
  319. valueheader.push_back('\x1C');
  320. valueheader.push_back('\x02');
  321. valueheader.push_back('\x28');
  322. valueheader.push_back((presetkeyvalue.size() >> 8) & 0xFF);
  323. valueheader.push_back((presetkeyvalue.size()) & 0xFF);
  324. valueheader.append(presetkeyvalue);
  325. tiffphotoshopdata.push_back('8');
  326. tiffphotoshopdata.push_back('B');
  327. tiffphotoshopdata.push_back('I');
  328. tiffphotoshopdata.push_back('M');
  329. tiffphotoshopdata.push_back('\x04');
  330. tiffphotoshopdata.push_back('\x04');
  331. tiffphotoshopdata.push_back('\x00');
  332. tiffphotoshopdata.push_back('\x00');
  333. tiffphotoshopdata.push_back((valueheader.size() >> 24) & 0xFF);
  334. tiffphotoshopdata.push_back((valueheader.size() >> 16) & 0xFF);
  335. tiffphotoshopdata.push_back((valueheader.size() >> 8) & 0xFF);
  336. tiffphotoshopdata.push_back((valueheader.size()) & 0xFF);
  337. tiffphotoshopdata.append(valueheader);
  338. TIFFSetField(tif, TIFFTAG_PHOTOSHOP, tiffphotoshopdata.size(), tiffphotoshopdata.c_str());
  339. }
  340. size_t pitch = width * bytesPerChannel * numChannels;
  341. char* raster = (char*) _TIFFmalloc((tsize_t)(pitch * height));
  342. memcpy(raster, pData, pitch * height);
  343. bRet = true;
  344. for (int h = 0; h < height; ++h)
  345. {
  346. size_t offset = h * pitch;
  347. int err = TIFFWriteScanline(tif, raster + offset, h, 0);
  348. if (err < 0)
  349. {
  350. bRet = false;
  351. break;
  352. }
  353. }
  354. _TIFFfree(raster);
  355. TIFFClose(tif);
  356. }
  357. return bRet;
  358. }
  359. const char* CImageTIF::GetPreset(const QString& fileName)
  360. {
  361. std::vector<uint8> data;
  362. CCryFile file;
  363. if (!file.Open(fileName.toUtf8().data(), "rb"))
  364. {
  365. CLogFile::FormatLine("File not found %s", fileName.toUtf8().data());
  366. return nullptr;
  367. }
  368. MemImage memImage;
  369. memImage.size = static_cast<uint32>(file.GetLength());
  370. data.resize(memImage.size);
  371. memImage.buffer = &data[0];
  372. memImage.offset = 0;
  373. file.ReadRaw(memImage.buffer, memImage.size);
  374. TIFF* tif = TIFFClientOpen (fileName.toUtf8().data(), "rm", (thandle_t)&memImage, libtiffDummyReadProc,
  375. libtiffDummyWriteProc, libtiffDummySeekProc,
  376. libtiffDummyCloseProc, libtiffDummySizeProc, libtiffDummyMapFileProc, libtiffDummyUnmapFileProc);
  377. AZStd::string strReturn;
  378. char* preset = nullptr;
  379. int size;
  380. if (tif)
  381. {
  382. TIFFGetField(tif, TIFFTAG_PHOTOSHOP, &size, &preset);
  383. for (int i = 0; i < size; ++i)
  384. {
  385. if (!strncmp((preset + i), "preset", 6))
  386. {
  387. char* presetoffset = preset + i;
  388. strReturn = presetoffset;
  389. if (strReturn.find('/') != -1)
  390. {
  391. strReturn = strReturn.substr(0, strReturn.find('/'));
  392. }
  393. break;
  394. }
  395. }
  396. TIFFClose(tif);
  397. }
  398. return strReturn.c_str();
  399. }