1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
// Copyright 2009-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "image.h"
#include <iostream>
#include <cstring>
#include <cstdio>
namespace embree
{
static void skipSpacesAndComments(std::fstream& file)
{
while (true)
{
if (isspace(file.peek())) {
file.ignore();
} else if (file.peek() == '#') {
std::string line; std::getline(file,line);
} else break;
}
}
/*! read PFM file from disk */
Ref<Image> loadPFM(const FileName& fileName)
{
/* open file for reading */
std::fstream file;
file.exceptions (std::fstream::failbit | std::fstream::badbit);
file.open (fileName.c_str(), std::fstream::in | std::fstream::binary);
/* read file type */
char cty[2]; file.read(cty,2);
skipSpacesAndComments(file);
std::string type(cty,2);
/* read width, height, and maximum color value */
int width; file >> width;
skipSpacesAndComments(file);
int height; file >> height;
skipSpacesAndComments(file);
float maxColor; file >> maxColor;
if (maxColor > 0) THROW_RUNTIME_ERROR("Big endian PFM files not supported");
float rcpMaxColor = -1.0f/float(maxColor);
file.ignore(); // skip space or return
/* create image and fill with data */
Ref<Image> img = new Image4f(width,height,fileName);
/* image in binary format 16 bit */
if (type == "PF")
{
float rgb[3];
for (ssize_t y=height-1; y>=0; y--) {
for (ssize_t x=0; x<width; x++) {
file.read((char*)rgb,sizeof(rgb));
img->set(x,y,Color4(rgb[0]*rcpMaxColor,rgb[1]*rcpMaxColor,rgb[2]*rcpMaxColor,1.0f));
}
}
}
/* invalid magic value */
else {
THROW_RUNTIME_ERROR("Invalid magic value in PFM file");
}
return img;
}
/*! store PFM file to disk */
void storePFM(const Ref<Image>& img, const FileName& fileName)
{
/* open file for writing */
std::fstream file;
file.exceptions (std::fstream::failbit | std::fstream::badbit);
file.open (fileName.c_str(), std::fstream::out | std::fstream::binary);
/* write file header */
file << "PF" << std::endl;
file << img->width << " " << img->height << std::endl;
file << -1.0f << std::endl;
/* write image */
for (ssize_t y=img->height-1; y>=0; y--) {
for (ssize_t x=0; x<(ssize_t)img->width; x++) {
const Color4 c = img->get(x,y);
file.write((char*)&c,3*sizeof(float));
}
}
}
}
|