void tileset::dropEvent(QDropEvent *event) { if (event->mimeData()->hasFormat(getMimeType()) && findPiece(targetSquare(event->pos())) == -1) { QByteArray pieceData = event->mimeData()->data(getMimeType()); QDataStream stream(&pieceData, QIODevice::ReadOnly); QRect square = targetSquare(event->pos()); int objID; stream >> objID; //QPixmap scaledPix = pixmap.scaled(m_baseSize, m_baseSize,Qt::KeepAspectRatio); QPixmap scaledPix = getScaledPixmapById(objID); piecePixmaps.append(scaledPix); pieceRects.append(square); pieceID.append(objID); highlightedRect = QRect(); update(); event->setDropAction(Qt::MoveAction); event->accept(); } else {
void tileset::dropEvent(QDropEvent *event) { if(event->mimeData()->hasFormat(getMimeType()) && findPiece(targetSquare(event->pos())) == -1) { QByteArray pieceData = event->mimeData()->data(getMimeType()); QDataStream stream(&pieceData, QIODevice::ReadOnly); QRect square = targetSquare(event->pos()); int objID; stream >> objID; QPixmap scaledPix; Items::getItemGFX(m_type, (unsigned long)objID, scaledPix, scn, false, QSize(m_baseSize, m_baseSize)); piecePixmaps.append(scaledPix); pieceRects.append(square); pieceID.append(objID); highlightedRect = QRect(); update(); event->setDropAction(Qt::MoveAction); event->accept(); }
/*! Tries to write the image object to the given output stream. Returns true on success. */ bool ImageFileType::write(const ImagePtr &image, std::ostream &os, const std::string &mimetype) { SWARNING << getMimeType() << " write to stream is not implemented" << endLog; return false; }
Configuration::FileType Configuration::getVolumeFormat(const QString & filepath) const { QFileInfo info(filepath); if(!info.exists()) { return UNKNOWN; } if(info.isDir()) { return DIRECTORY; } QString mimetype = getMimeType(info); if(mimetype.startsWith("image")) { return IMAGE; } else if(mimetype == QObject::tr("application/zip")) { return ZIP; } else if(mimetype == QObject::tr("application/x-rar")) { return RAR; } else if(mimetype == QObject::tr("application/pdf")) { return PDF; } else { qDebug() << "Mime detection failed, falling back onto file endings"; QString ending = filepath.split(".").last().toLower(); if(ending == ("pdf")) { return PDF; } else if(ending == ("zip") || ending == ("cbz")) { return ZIP; qDebug() << "Apparently its a zip"; } else if(ending == ("rar") || ending == ("cbr")) { return RAR; } else if(isSupportedImageFormat(ending)) { return IMAGE; } } qDebug() << "Don't know the file type, going with unknown..."; return UNKNOWN; }
/** * Reads and parses container mimetype. Checks that the mimetype is supported. * * @param path path to container directory. * @throws IOException exception is thrown if there was error reading mimetype file from disk. * @throws BDocException exception is thrown if the parsed mimetype is incorrect. */ void digidoc::BDoc::readMimetype(const std::string &path) throw(IOException, BDocException) { DEBUG("BDoc::readMimetype(path = '%s')", path.c_str()); // Read mimetype from file. std::string fileName = util::File::path(path, "mimetype"); std::ifstream ifs(util::File::encodeName(fileName).c_str(), std::ios::binary); unsigned char bom[] = { 0, 0, 0 }; ifs.read((char*)bom, sizeof(bom)); // Contains UTF-16 BOM if((bom[0] == 0xFF && bom[1] == 0xEF) || (bom[0] == 0xEF && bom[1] == 0xFF)) THROW_IOEXCEPTION("Mimetype file must be UTF-8 format.", fileName.c_str()); // does not contain UTF-8 BOM reset pos if(!(bom[0] == 0xEF && bom[1] == 0xBB && bom[2] == 0xBF)) ifs.seekg(0, std::ios::beg); std::string mimetype; ifs >> mimetype; ifs.close(); if(ifs.fail()) THROW_IOEXCEPTION("Failed to read mimetype file from '%s'.", fileName.c_str()); // Check that mimetype version is correct. DEBUG("mimetype = '%s'", mimetype.c_str()); if(getMimeType() != mimetype) THROW_BDOCEXCEPTION("Incorrect mimetype '%s', expecting '%s'", mimetype.c_str(), getMimeType().c_str()); }
void tileset::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat(getMimeType())) event->accept(); else event->ignore(); }
/*! Tries to fill the image object with the data read from the given input stream. Returns true on success. */ bool ImageFileType::read(ImagePtr &image, std::istream &is, const std::string &mimetype) { SWARNING << getMimeType() << " read from stream is not implemented" << endLog; return false; }
std::string MimeManager::getMimeType(std::string extension) { String mimeType; if(getMimeType(extension, mimeType)) return mimeType.to_ascii(); else return ""; }
/*! Tries to determine the mime type of the data provided by an input stream by searching for magic bytes. Returns the mime type or an empty string when the function could not determine the mime type. */ std::string JPGImageFileType::determineMimetypeFromStream(std::istream &is) { char filecode[2]; is.read(filecode, 2); is.seekg(-2, std::ios::cur); return strncmp(filecode, "\xff\xd8", 2) == 0 ? std::string(getMimeType()) : std::string(); }
bool Article::shouldCompress() const { std::string mimeType = getMimeType(); return mimeType != "image/jpeg" && mimeType != "image/png" && mimeType != "image/tiff" && mimeType != "image/gif" && mimeType != "application/zip"; }
/*! Abstract restore method. Should be overwriten by a concrete derived class. Tries to store the given image data to the given memblock */ UInt64 ImageFileType::storeData(const ImagePtr &, UChar8 *OSG_CHECK_ARG(buffer ), Int32 OSG_CHECK_ARG(memSize)) { FWARNING(("ImageXFileType::storeData() not impl. for mimeType %s\n", getMimeType())); return 0; }
/*! Tries to determine the mime type of the data provided by an input stream by searching for magic bytes. Returns the mime type or an empty string when the function could not determine the mime type. */ std::string PNGImageFileType::determineMimetypeFromStream(std::istream &is) { char filecode[4]; is.read(filecode, 4); is.seekg(-4, std::ios::cur); return strncmp(filecode, "\x89PNG", 4) == 0 ? std::string(getMimeType()) : std::string(); }
bool TGAImageFileType::write(const Image *, std::ostream &, const std::string &) { SWARNING << getMimeType() << " write is not compiled into the current binary " << std::endl; return true; }
/******************* FUNCTION *********************/ FileHttpNode::FileHttpNode(const std::string& path, const std::string& filePath, bool useCache, const std::string & mimeType) : HttpNode(path,true), filePath(filePath) { this->cache = NULL; this->size = -1; pthread_mutex_init(&mutex,NULL); if (mimeType == "auto") this->mimeType = getMimeType(filePath); this->useCache = useCache; }
static bool is_valid_extension (const char *extension) { if (!extension) return false; if (getMimeType (extension)) return true; return false; }
QVariant Playlist::parse(QString filename) { QStringList myList; QString filepath; QUrl url(filename); filepath = url.toLocalFile(); QFile file(filepath); if (!file.exists()) { qDebug() << "File: " << file.fileName() << "does not exist"; } if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "Couldn't open file: " << file.fileName(); } // check file type bool m3uType = false; QTextStream stream(&file); QString line = stream.readLine(); if (line.midRef(0,7) == "#EXTM3U" ) { //qDebug() << "valid M3U"; m3uType = true; } else { qDebug() << "invalid file type"; m3uType = false; } if (m3uType) { while(!stream.atEnd()) { QString line = stream.readLine(); if (line.midRef(0,8) == "#EXTINF:" ) { int d1 = line.indexOf(","); myList << line.mid(8,d1-8).trimmed(); // duration int d2 = line.indexOf(" - "); myList << line.mid(d1+1,d2-d1-1).trimmed(); // author myList << line.mid(d2+2,line.count()-d2+2).trimmed(); // title line = stream.readLine(); myList << line.trimmed(); // file myList << getMimeType(line); // mime type } else { } } } file.close(); return QVariant::fromValue(myList); }
WebCore::ResourceResponse WebResponse::createResourceResponse() { WebCore::ResourceResponse resourceResponse(createKurl(), getMimeType().c_str(), m_expectedSize, m_encoding.c_str(), ""); resourceResponse.setHTTPStatusCode(m_httpStatusCode); resourceResponse.setHTTPStatusText(m_httpStatusText.c_str()); map<string, string>::const_iterator it; for (it = m_headerFields.begin(); it != m_headerFields.end(); ++it) resourceResponse.setHTTPHeaderField(it->first.c_str(), it->second.c_str()); return resourceResponse; }
/** * Creates BDoc container manifest file and returns its path. * * Note: If non-ascii characters are present in XML data, we depend on the LANG variable to be set properly * (see iconv --list for the list of supported encoding values for libiconv). * * * @return returns created manifest file path. * @throws IOException exception is thrown if manifest file creation failed. */ std::string digidoc::BDoc::createManifest() throw(IOException) { DEBUG("digidoc::BDoc::createManifest()"); std::string fileName = util::File::tempFileName(); try { manifest::Manifest manifest; // Add container file entry with mimetype. manifest.file_entry().push_back(manifest::File_entry("/", getMimeType())); // Add documents with mimetypes. for(std::vector<Document>::const_iterator iter = documents.begin(); iter != documents.end(); iter++) { manifest::File_entry fileEntry(util::File::fileName(iter->getPath()), iter->getMediaType()); manifest.file_entry().push_back(fileEntry); } // Add signatures with mimetypes. unsigned int i = 0; for(std::vector<Signature*>::const_iterator iter = signatures.begin(); iter != signatures.end(); iter++) { manifest::File_entry fileEntry(util::String::format("META-INF/signature%u.xml", i++), (*iter)->getMediaType()); manifest.file_entry().push_back(fileEntry); } // Serialize XML to file. xml_schema::NamespaceInfomap map; map["manifest"].name = MANIFEST_NAMESPACE; DEBUG("Serializing manifest XML to '%s'", fileName.c_str()); // all XML data must be in UTF-8 std::ofstream ofs(digidoc::util::File::fstreamName(fileName).c_str()); manifest::manifest(ofs, manifest, map, "", xml_schema::Flags::dont_initialize); ofs.close(); if(ofs.fail()) { THROW_IOEXCEPTION("Failed to create manifest XML file to '%s'.", fileName.c_str()); } } catch(const xml_schema::Exception& e) { std::ostringstream oss; oss << e; THROW_IOEXCEPTION("Failed to create manifest XML file. Error: %s", oss.str().c_str()); } return fileName; }
/** * Creates mimetype file and returns its path. * * @return returns path to created mimetype file. * @throws IOException exception is thrown if file creation failed. */ std::string digidoc::BDoc::createMimetype() throw(IOException) { DEBUG("BDoc::createMimetype()"); // Create mimetype file. std::string fileName = util::File::tempFileName(); std::ofstream ofs(util::File::encodeName(fileName).c_str()); ofs << getMimeType(); ofs.close(); if(ofs.fail()) THROW_IOEXCEPTION("Failed to create mimetype file to '%s'.", fileName.c_str()); return fileName; }
void tileset::dragMoveEvent(QDragMoveEvent *event) { if (event->mimeData()->hasFormat(getMimeType()) && findPiece(targetSquare(event->pos())) == -1) { highlightedRect = targetSquare(event->pos()); event->setDropAction(Qt::MoveAction); event->accept(); } else { highlightedRect = QRect(); event->ignore(); } update(); }
/*! The dump method just writes some object debugging info to the LOG stream */ void ImageFileType::dump(void) { std::list<IDString>::iterator sI; SLOG << getMimeType(); if(_suffixList.empty()) { SLOG << ": Suffix: "; for(sI = _suffixList.begin(); sI != _suffixList.end(); sI++) { Log().stream(OSG::LOG_DEBUG) << sI->str() << " "; } } std::cerr << std::endl; }
QMimeData * ListWidget::mimeData(const QList<QListWidgetItem *> items) const { QMimeData * mimeData = QListWidget::mimeData(items); mimeData->setData(getMimeType(),QByteArray()); QString string; for(int i=0; i<items.size(); i++){ QListWidgetItem * item = items.at(i); string += item->text(); if(i < items.size() -1){ string += ","; } } mimeData->setText(string); return mimeData; }
boost::shared_ptr<Response> ResponseBuilder::build(ushort status, std::string bodyExtension, const char *body, size_t bodySize) { std::stringstream headers; const char *delimiter = "\r\n"; headers << "HTTP/1.1 " << status << " " << getStatusName(status) << delimiter; headers << "Date: " << getDate() << delimiter; headers << "Server: " << "HttpServer/1.1" << delimiter; headers << "Content-Length: " << bodySize << delimiter; headers << "Content-Type: " << getMimeType(bodyExtension) << delimiter; headers << "Connection: " << "close" << delimiter; headers << delimiter; //std::cout << "Response headers:" << std::endl << headers.str(); return boost::make_shared<Response>(headers.str(), body, bodySize); }
QByteArray KoScriptingOdfStore::getByteArray() { if (! m_byteArray.isNull()) return m_byteArray; if (m_readStore) { //kDebug(32010) << "KoScriptingOdfStore::getByteArray() Cleaning prev cached store up."; if (m_readStore->isOpen() ) { //kDebug(32010) << "KoScriptingOdfStore::getByteArray() Closing prev cached store."; m_readStore->close(); } delete m_readStore; m_readStore = 0; } if (m_readDevice) { //kDebug(32010) << "KoScriptingOdfStore::getByteArray() Cleaning prev cached device up."; delete m_readDevice; m_readDevice = 0; } if (! m_document) { //kWarning(32010) << "KoScriptingOdfStore::getByteArray() No document defined."; return QByteArray(); } //kDebug(32010) << "KoScriptingOdfStore::getByteArray() Reading ByteArray."; QBuffer buffer(&m_byteArray); KoStore *store = KoStore::createStore(&buffer, KoStore::Write, "KrossScript", KoStore::Tar); KoOdfWriteStore odfStore(store); odfStore.manifestWriter(""); KoEmbeddedDocumentSaver embeddedSaver; KoDocument::SavingContext documentContext(odfStore, embeddedSaver); QByteArray mime = getMimeType(); if (! m_document->saveOdf(documentContext)) { kWarning(32010) << "KoScriptingOdfStore::open() Failed to save Oasis to ByteArray"; m_byteArray = QByteArray(); } //odfStore.closeContentWriter(); odfStore.closeManifestWriter(); delete store; return m_byteArray; }
/** * Reads and parses container mimetype. Checks that the mimetype is supported. * * @param path path to container directory. * @throws IOException exception is thrown if there was error reading mimetype file from disk. * @throws BDocException exception is thrown if the parsed mimetype is incorrect. */ void digidoc::BDoc::readMimetype(std::string path) throw(IOException, BDocException) { DEBUG("BDoc::readMimetype(path = '%s')", path.c_str()); // Read mimetype from file. std::string fileName = util::File::path(path, "mimetype"); std::ifstream ifs(util::File::fstreamName(fileName).c_str()); std::string mimetype; ifs >> mimetype; ifs.close(); if(ifs.fail()) { THROW_IOEXCEPTION("Failed to read mimetype file from '%s'.", fileName.c_str()); } // Check that mimetype version is correct. DEBUG("mimetype = '%s'", mimetype.c_str()); if(getMimeType().compare(mimetype) != 0) { THROW_BDOCEXCEPTION("Incorrect mimetype '%s', expecting '%s'", mimetype.c_str(), getMimeType().c_str()); } }
void HttpProtocolData::initTask(HttpTask *task) { LOG(0, "enter initTask, task = %p\n", task); HttpSession *ses = task->sessions[0]; TaskInfo *info = task->info; CURL *ehandle = ses->handle; char logBuffer[64] = {0}; info->mimeType = getMimeType(ehandle, info->uri); snprintf(logBuffer, 63, "mime type: %s", info->mimeType.c_str()); info->taskLog(info, logBuffer); // get file information. double length; if (info->outputName.length() == 0) info->outputName = getFileName(ehandle, info->uri); std::string output = info->outputPath; output.append(info->outputName); if (info->totalSize == 0) { File::remove(output.c_str()); } task->file.open(output.c_str(), OF_Create | OF_Write); if (!task->file.isOpen()) throw DOWNLOADEXCEPTION(FAIL_OPEN_FILE, "HTTP", strerror(FAIL_OPEN_FILE)); snprintf(logBuffer, 63, "File path: %s", output.c_str()); info->taskLog(info, logBuffer); if (info->totalSize == 0) { CURLcode rete = curl_easy_getinfo(ehandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &length); CHECK_CURLE(rete); if (length > 0) { info->totalSize = static_cast<size_t>(length); info->downloadMap = BitMap(size_t(length), task->conf.bytesPerBlock); info->downloadMap.setAll(false); info->validMap = BitMap(size_t(length), task->conf.bytesPerBlock); info->validMap.setAll(true); snprintf(logBuffer, 63, "File length: %lu", info->totalSize); info->taskLog(info, logBuffer); task->file.resize(info->totalSize); } else if (length < 0) info->totalSize = 0; else // length == 0, zero length file return; } info->totalSource = info->validSource = 1; if (info->totalSize > 0) // may equal 0 mean unknow length. { LOG(0, "make download sessions\n"); // seperate download part in 2 steps: // 1 give each non-download part a session; // 2 find a biggest part and divide, repeat till enough session. unsigned int begin = ses->pos / info->downloadMap.bytesPerBit(); unsigned int end = info->downloadMap.find(true, begin); unsigned int nextBegin = info->downloadMap.find(false, end); ses->length = (end - begin) * info->downloadMap.bytesPerBit(); int i = 1; begin = nextBegin; while ( (i < task->conf.sessionNumber) && (begin < info->downloadMap.size()) ) { end = info->downloadMap.find(true, begin); nextBegin = info->downloadMap.find(false, end); // make [begin, end) a seesion. makeSession(task, begin * info->downloadMap.bytesPerBit(), (end - begin) * info->downloadMap.bytesPerBit()); ++i; begin = nextBegin; } while (i < task->conf.sessionNumber) { if (!splitMaxSession(task)) { break; } ++i; } } task->state = HT_DOWNLOAD; }
std::string TrackingSyncSource::getPeerMimeType() const { return getMimeType(); }
void wFileProps::createGUI() { QString mimeType = getMimeType( fileName ); QFontDatabase fdb = QFontDatabase(); fdb.addApplicationFont( ":/fonts/ArchitectsDaughter.ttf" ); setStyleSheet( "font-family: Architects Daughter; font-size: 10;" ); iconLbl = new QLabel(); iconLbl->setPixmap( getPixmap( fileName ).scaled( 64, 64, Qt::KeepAspectRatio ) ); nameLbl = new QLabel(); nameLbl->setText( "<b>" + QFileInfo( fileName ).fileName() + "</b>" ); nameLbl->setFont( QFont( "Architects Daughter", 15 ) ); linesLbl = new QLabel( lines ); wordsLbl = new QLabel( words ); charsLbl= new QLabel( chars ); if ( !noFileProps ) { typeLbl = new QLabel( mimeType ); sizeLbl = new QLabel( formatSize( getSize( fileName ) ) ); locLbl = new QLabel( QFileInfo( fileName ).absolutePath() ); time1Lbl = new QLabel( QFileInfo( fileName ).created().toString( "ddd MMM dd, yyyy hh:mm:ss" ) ); time2Lbl = new QLabel( QFileInfo( fileName ).lastRead().toString( "ddd MMM dd, yyyy hh:mm:ss" ) ); time3Lbl = new QLabel( QFileInfo( fileName ).lastModified().toString( "ddd MMM dd, yyyy hh:mm:ss" ) ); } QPushButton *closeBtn = new QPushButton(); closeBtn->setText( "&Close" ); connect( closeBtn, SIGNAL( clicked() ), this, SLOT( close() ) ); QVBoxLayout *baseLyt = new QVBoxLayout(); QHBoxLayout *nameLyt = new QHBoxLayout(); QFormLayout *textInfoLyt = new QFormLayout(); QFormLayout *fileInfoLyt = new QFormLayout(); QHBoxLayout *btnLyt = new QHBoxLayout(); nameLyt->setAlignment( Qt::AlignCenter ); nameLyt->addWidget( iconLbl ); nameLyt->addWidget( nameLbl ); textInfoLyt->addRow( new QLabel( "<b>Lines: </b>" ), linesLbl ); textInfoLyt->addRow( new QLabel( "<b>Words: </b>" ), wordsLbl ); textInfoLyt->addRow( new QLabel( "<b>Chars: </b>" ), charsLbl ); textInfoLyt->setFormAlignment( Qt::AlignHCenter | Qt::AlignTop ); if ( !noFileProps ) { fileInfoLyt->addRow( new QLabel( "<b>Type: </b>" ), typeLbl ); fileInfoLyt->addRow( new QLabel( "<b>Size: </b>" ), sizeLbl ); fileInfoLyt->addRow( new QLabel( "<b>Location: </b>" ), locLbl ); fileInfoLyt->addRow( new QLabel( "<b>Created: </b>" ), time1Lbl ); fileInfoLyt->addRow( new QLabel( "<b>Accessed: </b>" ), time2Lbl ); fileInfoLyt->addRow( new QLabel( "<b>Modified: </b>" ), time3Lbl ); } btnLyt->addStretch( 0 ); btnLyt->addWidget( closeBtn ); btnLyt->addStretch( 0 ); QFrame *textFrame = new QFrame(); textFrame->setFrameStyle( QFrame::StyledPanel | QFrame::Plain ); textFrame->setLayout( textInfoLyt ); QFrame *fileFrame = new QFrame(); fileFrame->setFrameStyle( QFrame::StyledPanel | QFrame::Plain ); fileFrame->setLayout( fileInfoLyt ); baseLyt->addLayout( nameLyt ); baseLyt->addStretch( 0 ); baseLyt->addWidget( textFrame ); if ( !noFileProps ) { baseLyt->addStretch( 0 ); baseLyt->addWidget( fileFrame ); } baseLyt->addStretch( 0 ); baseLyt->addLayout( btnLyt ); setLayout( baseLyt ); };
/*! Tries to write the image object to the given output stream. Returns true on success. */ bool EXRImageFileType::write(const Image *image, std::ostream &os, const std::string &mimetype) { #ifdef OSG_WITH_IMF if (!os.good()) return false; if(image->getDataType() != Image::OSG_FLOAT16_IMAGEDATA) { FWARNING(("EXRImageFileType::write: Image has non float data type!\n")); return false; } if(image->getComponents() != 4) { FWARNING(("EXRImageFileType::write: Image has != 4 components!\n")); return false; } if (image->getSideCount() == 6) { FWARNING(("EXRImageFileType::write: NYI for cubemaps\n")); //TODO return false; } try { Int32 width = image->getWidth(); Int32 height = image->getHeight(); const char *dummy = ""; StdOStream file(os, dummy); Imf::Header header(width, height); #if 0 // now add custom attributes ImageGenericAtt *att = dynamic_cast<ImageGenericAtt *>( image->findAttachment( ImageGenericAtt::getClassType().getGroupId())); if(att != NULL) { FieldContainerType &fcType = att->getType(); Int32 count = att->getType().getNumFieldDescs(); for(Int32 i = 1; i <= count; ++i) { FieldDescriptionBase *fDesc = fcType.getFieldDesc(i); Field *field = att->getField(i); if(fDesc != NULL && field != NULL) { SFString *strField = dynamic_cast<SFString*>(field); if(strField != NULL) { Imf::StringAttribute imfAttr( strField->getValue().c_str()); header.insert(fDesc->getCName(), imfAttr); } } } } #endif // we write each side as 4 channels out // side 0 RGBA // side 1 R1G1B1A1 // ... for(Int32 side=0;side<image->getSideCount();++side) { char cn[20]; sprintf(cn, "%d", side); char name[20]; sprintf(name, "R%s", side == 0 ? "" : cn); header.channels().insert(name, Imf::Channel(Imf::HALF)); sprintf(name, "G%s", side == 0 ? "" : cn); header.channels().insert(name, Imf::Channel(Imf::HALF)); sprintf(name, "B%s", side == 0 ? "" : cn); header.channels().insert(name, Imf::Channel(Imf::HALF)); sprintf(name, "A%s", side == 0 ? "" : cn); header.channels().insert(name, Imf::Channel(Imf::HALF)); } Imf::OutputFile stream(file, header); Imf::FrameBuffer frame_buffer; // we need to do a vertical flip so we write single scan lines out. for(int i=height-1;i>=0;--i) { for(Int32 side=0;side<image->getSideCount();++side) { const char *data = (reinterpret_cast<const char *>(image->getData(0, 0, side))) + i * (sizeof(Real16) * 4 * width); // writePixels() adds the current scan line index as an offset to the // base address we need to eliminate this! data -= stream.currentScanLine() * (sizeof(Real16) * 4 * width); char cn[20]; sprintf(cn, "%d", side); char name[20]; sprintf(name, "R%s", side == 0 ? "" : cn); frame_buffer.insert(name, Imf::Slice(Imf::HALF, const_cast<char *>(data), sizeof(Real16) * 4, sizeof(Real16) * 4 * width)); sprintf(name, "G%s", side == 0 ? "" : cn); frame_buffer.insert(name, Imf::Slice(Imf::HALF, const_cast<char *>(data) + 1 * sizeof(Real16), sizeof(Real16) * 4, sizeof(Real16) * 4 * width)); sprintf(name, "B%s", side == 0 ? "" : cn); frame_buffer.insert(name, Imf::Slice(Imf::HALF, const_cast<char *>(data) + 2 * sizeof(Real16), sizeof(Real16) * 4, sizeof(Real16) * 4 * width)); sprintf(name, "A%s", side == 0 ? "" : cn); frame_buffer.insert(name, Imf::Slice(Imf::HALF, const_cast<char *>(data) + 3 * sizeof(Real16), sizeof(Real16) * 4, sizeof(Real16) * 4 * width)); } stream.setFrameBuffer(frame_buffer); stream.writePixels(1); } return true; } catch(std::exception &e) { FFATAL(( "Error while trying to write OpenEXR Image from stream: %s\n", e.what() )); return false; } #else SWARNING << getMimeType() << " write is not compiled into the current binary " << std::endl; return false; #endif }
/*! Tries to fill the image object with the data read from the given input stream. Returns true on success. */ bool EXRImageFileType::read( Image *image, std::istream &is, const std::string &mimetype) { #ifdef OSG_WITH_IMF if (!is.good()) return false; const char *dummy = ""; StdIStream file(is, dummy); Imf::Int64 pos = file.tellg(); bool check = isOpenExrFile(is); file.seekg(pos); if (!check) { FFATAL(( "Wrong format, no %s image given!\n", mimetype.c_str() )); return false; } // just read the header and get the channel count int channel_count = 0; pos = file.tellg(); try { Imf::RgbaInputFile stream(file); const Imf::Header &header = stream.header(); const Imf::ChannelList &channels = header.channels(); for(Imf::ChannelList::ConstIterator it = channels.begin(); it != channels.end(); ++it) { ++channel_count; } } catch(std::exception &e) { FFATAL(( "Error while trying to read OpenEXR Image from stream: %s\n", e.what() )); return false; } file.seekg(pos); if(channel_count <= 4) { // TODO: check for mipmap levels, // look if line order is s.th. else than INCREASING_Y try { Int32 width, height, numImg = 1; Imf::RgbaInputFile stream(file); Imath::Box2i dw = stream.dataWindow(); Imf::Array2D<Imf::Rgba> pixels; const Imf::Header &header = stream.header(); // const Imf::LineOrder &order = header.lineOrder(); const Imf::EnvmapAttribute *envmap = header.findTypedAttribute<Imf::EnvmapAttribute>("envmap"); width = dw.max.x - dw.min.x + 1; height = dw.max.y - dw.min.y + 1; pixels.resizeErase(height, width); if(envmap && envmap->value() == Imf::ENVMAP_CUBE) { numImg = 6; height /= numImg; if (width != height) { FFATAL(( "Cubemaps must have squared size, " "but w=%d and h=%d!\n", width, height )); return false; } } stream.setFrameBuffer(&pixels[0][0] - dw.min.x - dw.min.y * width, 1, width); stream.readPixels(dw.min.y, dw.max.y); image->set( Image::OSG_RGBA_PF, width, height, 1, 1, 1, 0, 0, Image::OSG_FLOAT16_IMAGEDATA, true, numImg ); image->clearHalf(); // now add custom attributes for(Imf::Header::ConstIterator it = header.begin(); it != header.end(); ++it) { Imf::Attribute *copy = it.attribute().copy(); Imf::StringAttribute *sa = dynamic_cast<Imf::StringAttribute *>(copy); if(sa != NULL) image->setAttachmentField(it.name(), sa->value()); delete copy; } Real16 *data = reinterpret_cast<Real16*>(image->editData()); for (Int32 side=numImg-1; side >=0; side--) { Int32 i, j, size = side * width * height * 4; for (Int32 y=side*height; y<(side+1)*height; y++) { for (Int32 x=0; x<width; x++) { if (numImg == 1 || side == 2 || side == 3) { i = (2 * side + 1) * height - (y + 1); // new y j = x; } else { i = y; j = width - x - 1; // new x } *(data + size++) = Real16(pixels[i][j].r); *(data + size++) = Real16(pixels[i][j].g); *(data + size++) = Real16(pixels[i][j].b); *(data + size++) = Real16(pixels[i][j].a); } } } return true; } catch(std::exception &e) { FFATAL(( "Error while trying to read OpenEXR Image from stream: " "%s\n", e.what() )); return false; } } else { try { if(channel_count % 4 != 0) { FFATAL(( "Error while trying to read OpenEXR Image from " "stream, channel count of %d is not supported!\n", channel_count)); return false; } int num_img = channel_count / 4; Imf::InputFile stream(file); const Imf::Header &header = stream.header(); Imath::Box2i dw = header.dataWindow(); int width = dw.max.x - dw.min.x + 1; int height = dw.max.y - dw.min.y + 1; image->set(Image::OSG_RGBA_PF, width, height, 1, 1, 1, 0, 0, Image::OSG_FLOAT16_IMAGEDATA, true, num_img); image->clearHalf(); // now add custom attributes for(Imf::Header::ConstIterator it = header.begin(); it != header.end(); ++it ) { Imf::Attribute *copy = it.attribute().copy(); Imf::StringAttribute *sa = dynamic_cast<Imf::StringAttribute *>(copy); if(sa != NULL) image->setAttachmentField(it.name(), sa->value()); delete copy; } const Imf::ChannelList &channels = header.channels(); // do some channel name checks bool channel_error = false; for(Imf::ChannelList::ConstIterator it=channels.begin();it!=channels.end();++it) { for(int side=0;side>num_img;++side) { char cn[20]; sprintf(cn, "%d", side); char name[20]; sprintf(name, "R%s", side == 0 ? "" : cn); if(channels.findChannel(name) == NULL) channel_error = true; sprintf(name, "G%s", side == 0 ? "" : cn); if(channels.findChannel(name) == NULL) channel_error = true; sprintf(name, "B%s", side == 0 ? "" : cn); if(channels.findChannel(name) == NULL) channel_error = true; sprintf(name, "A%s", side == 0 ? "" : cn); if(channels.findChannel(name) == NULL) channel_error = true; } } if(channel_error) { FFATAL(( "Error while trying to read OpenEXR Image from " "stream, expected channel names 'R' 'G' 'B' 'A', " "'R1' 'G1', 'B1', 'A1', ...\n")); return false; } Imf::FrameBuffer frame_buffer; // we need to do a vertical flip so we read single scan lines in. int current_scan_line = 0; for(int i=height-1;i>=0;--i) { for(int side=0;side<num_img;++side) { char *data = (reinterpret_cast<char *>(image->editData(0, 0, side))) + i * (sizeof(Real16) * 4 * width); data -= current_scan_line * (sizeof(Real16) * 4 * width); char cn[20]; sprintf(cn, "%d", side); char name[20]; sprintf(name, "R%s", side == 0 ? "" : cn); frame_buffer.insert(name, Imf::Slice(Imf::HALF, data, sizeof(Real16) * 4, sizeof(Real16) * 4 * width)); sprintf(name, "G%s", side == 0 ? "" : cn); frame_buffer.insert(name, Imf::Slice(Imf::HALF, data + 1 * sizeof(Real16), sizeof(Real16) * 4, sizeof(Real16) * 4 * width)); sprintf(name, "B%s", side == 0 ? "" : cn); frame_buffer.insert(name, Imf::Slice(Imf::HALF, data + 2 * sizeof(Real16), sizeof(Real16) * 4, sizeof(Real16) * 4 * width)); sprintf(name, "A%s", side == 0 ? "" : cn); frame_buffer.insert(name, Imf::Slice(Imf::HALF, data + 3 * sizeof(Real16), sizeof(Real16) * 4, sizeof(Real16) * 4 * width)); } stream.setFrameBuffer(frame_buffer); stream.readPixels(current_scan_line, current_scan_line); ++current_scan_line; } return true; } catch(std::exception &e) { FFATAL(( "Error while trying to read OpenEXR Image from stream: %s\n", e.what() )); return false; } } #else SWARNING << getMimeType() << " read is not compiled into the current binary " << std::endl; return false; #endif }