static PyObject *meth_QImageWriter_setFormat(PyObject *sipSelf, PyObject *sipArgs)
{
    PyObject *sipParseErr = NULL;

    {
        const QByteArray* a0;
        int a0State = 0;
        QImageWriter *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "BJ1", &sipSelf, sipType_QImageWriter, &sipCpp, sipType_QByteArray, &a0, &a0State))
        {
            Py_BEGIN_ALLOW_THREADS
            sipCpp->setFormat(*a0);
            Py_END_ALLOW_THREADS
            sipReleaseType(const_cast<QByteArray *>(a0),sipType_QByteArray,a0State);

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    /* Raise an exception if the arguments couldn't be parsed. */
    sipNoMethod(sipParseErr, sipName_QImageWriter, sipName_setFormat, doc_QImageWriter_setFormat);

    return NULL;
}
void diff_images(QImage *image1, QImage *image2, QString fileName)
{
    // TODO: Check images size

    QImage* image3 = new QImage(image1->size(), QImage::Format_RGB32);

    for (int i = 0; i < image1->size().width(); i++) {
        for (int j = 0; j < image1->size().height(); j++) {
            int p1 = qGray(image1->pixel(i,j));
            int p2 = qGray(image2->pixel(i,j));
            int p3 = p1-p2;
            double fSigma = 0.4 * 25.0;
            double diff = (static_cast<double>(p3)+ fSigma) * 255.0 / (2.0 * fSigma);
            if (diff < 0.0) diff = 0;
            if (diff > 255.5) diff = 255;
            p3 = diff;
            image3->setPixel(i,j,qRgb(p3,p3,p3));
        }
    }

    QImageWriter* imageDiff = new QImageWriter();
    imageDiff->setFileName(fileName);
    imageDiff->write(*image3);

    delete image3;
    delete imageDiff;
}
void GraphicColumnWidget::slotExportToTiff() {
    QString fn = QFileDialog::getSaveFileName(this,
            tr("Export Profile To Tiff..."),
            QDir::currentPath(),
            tr("TIFF Files (*.tif *.tiff *.Tif *.TIF *.TIFF *.Tiff)"));
    if (fn.isEmpty()) {
        return;
    }

    QImageWriter w;
    w.setFileName(fn);
    w.setFormat("TIFF");

    QImage img(QSize((int)(_scene->width()), (int)(_scene->height())), QImage::Format_RGB32);
    QPainter painter(&img);
    painter.setRenderHint(QPainter::Antialiasing);
    _scene->render(&painter);
    painter.end();

    if (w.write(img)) {
        QMessageBox::information(this, tr("Export Completed"),
                tr("Profile exported to <b>%1</b>.").arg(fn));
    } else {
        QMessageBox::critical(this, tr("Export Failed"),
                tr("Could not export Profile: %1").arg(w.errorString()));
    }
}
Beispiel #4
0
void image::sSave()
{
  XSqlQuery newImage;

  if (__image.isNull())
  {
    QMessageBox::warning(this, tr("No Image Specified"),
      tr("You must load an image before you may save this record.") );
    return;
  }

  if (_mode == cNew)
  {
    XSqlQuery imageid("SELECT NEXTVAL('image_image_id_seq') AS _image_id");
    if (imageid.first())
      _imageid = imageid.value("_image_id").toInt();
//  ToDo

    QImageWriter imageIo;
    QBuffer  imageBuffer;
    QString  imageString;

    imageBuffer.open(QIODevice::ReadWrite);
    imageIo.setDevice(&imageBuffer);
    imageIo.setFormat("PNG");

    if (!imageIo.write(__image))
    {
      QMessageBox::critical(this, tr("Error Saving Image"),
        tr("There was an error trying to save the image.") );
      return;
    }

    imageBuffer.close();
    imageString = QUUEncode(imageBuffer);

    newImage.prepare( "INSERT INTO image "
                      "(image_id, image_name, image_descrip, image_data) "
                      "VALUES "
                      "(:image_id, :image_name, :image_descrip, :image_data);" );
    newImage.bindValue(":image_id", _imageid);
    newImage.bindValue(":image_name", _name->text());
    newImage.bindValue(":image_descrip", _descrip->toPlainText());
    newImage.bindValue(":image_data", imageString);
  }
  else if (_mode == cEdit)
  {
    newImage.prepare( "UPDATE image "
                      "SET image_name=:image_name, image_descrip=:image_descrip "
                      "WHERE (image_id=:image_id);" );
    newImage.bindValue(":image_id", _imageid);
    newImage.bindValue(":image_name", _name->text());
    newImage.bindValue(":image_descrip", _descrip->toPlainText());
  }

  newImage.exec();

  done(_imageid);
}
Beispiel #5
0
int main(int argv, char **args)
{
//! [0]
	QImageWriter writer;
	writer.setFormat("png");
	if (writer.supportsOption(QImageIOHandler::Description))
	    qDebug() << "Png supports embedded text";
//! [0]
    return 0;
}
void imageview::sSave()
{
  XSqlQuery newImage;

  if (_mode == cNew)
  {
    if (!__imageview.isNull())
    {
      XSqlQuery imageid("SELECT NEXTVAL('image_image_id_seq') AS _image_id");
      if (imageid.first())
        _imageviewid = imageid.value("_image_id").toInt();
//  ToDo
 
      QImageWriter imageIo;
      QBuffer  imageBuffer;
      QString  imageString;

      imageBuffer.open(QIODevice::ReadWrite);
      imageIo.setDevice(&imageBuffer);
      imageIo.setFormat("PNG");

      if (!imageIo.write(__imageview))
      {
//  ToDo - should issue an error here
        reject();
        return;
      }

      imageBuffer.close();
      imageString = QUUEncode(imageBuffer);

      newImage.prepare( "INSERT INTO image "
                        "(image_id, image_name, image_descrip, image_data) "
                        "VALUES "
                        "(:image_id, :image_name, :image_descrip, :image_data);" );
      newImage.bindValue(":image_id", _imageviewid);
      newImage.bindValue(":image_name", _name->text());
      newImage.bindValue(":image_descrip", _descrip->toPlainText());
      newImage.bindValue(":image_data", imageString);
    }
  }
  else if (_mode == cEdit)
  {
    newImage.prepare( "UPDATE image "
                      "SET image_name=:image_name, image_descrip=:image_descrip "
                      "WHERE (image_id=:image_id);" );
    newImage.bindValue(":image_id", _imageviewid);
    newImage.bindValue(":image_name", _name->text());
    newImage.bindValue(":image_descrip", _descrip->toPlainText());
  }

  newImage.exec();

  done(_imageviewid);
}
Beispiel #7
0
QStringList MainWindow::do_run_jobs(QMap<QString, rc_map> &jobs)
{
	QStringList failed, succeeded;
	QString propaganda = QString("Generated by Morning Star v%1").arg(mos_version);
	this->setEnabled(false);

	for(QMap<QString, rc_map>::const_iterator k = jobs.begin(); k != jobs.end(); ++k) {
		QImage rc;
		QImageWriter out;
		out.setFormat("png");
		out.setFileName(k.key());
		out.setText("", propaganda);

		if(rc_image(this->img_original_, rc, k.value()) && out.write(rc)) {
			succeeded.push_back(out.fileName());
		}
		else {
			failed.push_back(out.fileName());
		}
	}

	this->setEnabled(true);

	if(failed.isEmpty() != true) {
		throw failed;
	}

	return succeeded;
}
Beispiel #8
0
bool SaveFilter::saveFullImage(const QuillImage &image) const
{
    QImageWriter *writer;
    if (priv->iODevice)
        writer = new QImageWriter(priv->iODevice, priv->fileFormatQt.toLatin1());
    else
        writer = new QImageWriter(priv->fileName);

    if (!priv->fileFormatQt.isNull())
        writer->setFormat(priv->fileFormatQt.toLatin1());

    bool ok = writer->write(image);

    if (!ok)
        const_cast<SaveFilter *>(this)->setError(writer->error());

    delete writer;
    return ok;
}
void MainWindow::exportImage() {

    QVector<CPoint> centroids = nGas.getCentroids();
    QVector<KPoint> points = nGas.getPoints();

    QImage image(imageSize,QImage::Format_RGB32);

    QProgressDialog progress(this);
    progress.setWindowTitle("Self-organizing maps");
    progress.setLabelText("Generating file...");
    progress.setModal(true);
    progress.show();

    int k = 0;

    for(int i=0;i<image.width();i++) {
        progress.setValue(((double)i / (double)image.width()) * 100);
        if(progress.wasCanceled())
            return;

        for(int j=0;j<image.height();j++) {
            for(int d=0;d<centroids.size();d++)
                centroids[d].setDistance(Centroids::countDistance(centroids[d],points[k]));
            qSort(centroids.begin(),centroids.end(),SortByDistance());
            image.setPixel(i,j,qRgb(centroids[0].paramAt(0),centroids[1].paramAt(1),centroids[2].paramAt(2)));
            k++;
        }
    }

    progress.setValue(100);

    QGraphicsScene* scene = new QGraphicsScene(this);
    ui->graphicsView_2->setScene(scene);
    scene->addPixmap(QPixmap::fromImage(image.scaled(ui->graphicsView->width()*0.95,ui->graphicsView->height()*0.95)));
    ui->graphicsView_2->show();

    QImageWriter writer;
    writer.setFileName(QFileDialog::getSaveFileName(this,tr("Open image"),"C:\\Users\\GiBSoN\\Desktop",tr("Image files (*.jpg *.png)")));
    writer.setFormat("jpg");
    writer.setCompression(10);
    writer.write(image);
}
Beispiel #10
0
void OpenGLHelpers::takeSnapshot(QString filename, int width, int height, int startY){
    uchar * imageData = new uchar[4*width * height];
    glReadPixels(0, startY,width, height,GL_BGRA,GL_UNSIGNED_BYTE,(void *)imageData);
    int * vals = (int*)imageData, * lo, * hi;

    for(int row = 0; row < height/2; ++row){
        hi = vals+row*width;
        lo = vals + (height - 1 - row)*width;
        for(int i = 0; i < width ; ++i)
            std::swap(hi[i],lo[i]);
    }

    QImage img = QImage(imageData,width,height,QImage::Format_ARGB32);
    QImageWriter * writer = new QImageWriter(filename);
    writer->setFormat("jpg");
    writer->setQuality(100);
    writer->write(img);

    delete writer;
    delete [] imageData;
}
Beispiel #11
0
static QByteArray randomJPEGByteArray(int w=512, int h=512, int q=85 )
{
	QImage image=randomImage(w,h);
	QBuffer bu;
	bu.open(QBuffer::WriteOnly);
	QImageWriter iw;
	iw.setFormat("jpeg");
	iw.setDevice(&bu);
	iw.setOptimizedWrite(true );
	iw.setQuality(q);
	iw.setCompression(9);
	iw.setProgressiveScanWrite(true );
	iw.write( image );
	bu.close();
	QByteArray ba=bu.buffer();
	//utility::byteArrayToFile("random_test.jpeg",ba );
	//qDebug()<<"Random JPEG image of size "<<w<<"x"<<h<<" was "<< utility::humanReadableSize(ba.size())<< "("<<(qreal)ba.size()/((qreal)w*h) << " bytes/pixel)";
	return ba;

}
Beispiel #12
0
/**
 * @return Path to the thumbnail of the given DXF file. If no thumbnail exists, one is
 * created in the user's home. If no thumbnail can be created, an empty string is returned.
 */
QString QG_LibraryWidget::getPathToPixmap(const QString& dir,
        const QString& dxfFile,
        const QString& dxfPath) {

    // the thumbnail must be created in the user's home.
#if QT_VERSION < 0x040400
    QString iconCacheLocation = emu_qt44_storageLocationData() + QDir::separator() + "iconCache" + QDir::separator();
#elif QT_VERSION >= 0x050000
    QString iconCacheLocation=QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QDir::separator() + "iconCache" + QDir::separator();
#else
    QString iconCacheLocation=QDesktopServices::storageLocation(QDesktopServices::DataLocation) + QDir::separator() + "iconCache" + QDir::separator();
#endif

    RS_DEBUG->print("QG_LibraryWidget::getPathToPixmap: "
                    "dir: '%s' dxfFile: '%s' dxfPath: '%s'",
                    dir.toLatin1().data(), dxfFile.toLatin1().data(), dxfPath.toLatin1().data());

    // List of all directories that contain part libraries:
    QStringList directoryList = RS_SYSTEM->getDirectoryList("library");
    directoryList.prepend(iconCacheLocation);
    QStringList::Iterator it;

    QFileInfo fiDxf(dxfPath);
    QString itemDir;
    QString pngPath;

    // look in all possible system directories for PNG files
    //  in the current library path:
    for (it=directoryList.begin(); it!=directoryList.end(); ++it) {
        itemDir = (*it)+dir;
        pngPath = itemDir + QDir::separator() + fiDxf.baseName() + ".png";
        RS_DEBUG->print("QG_LibraryWidget::getPathToPixmap: checking: '%s'",
                        pngPath.toLatin1().data());
        QFileInfo fiPng(pngPath);

        // the thumbnail exists:
        if (fiPng.isFile()) {
            RS_DEBUG->print("QG_LibraryWidget::getPathToPixmap: dxf date: %s, png date: %s",
                            fiDxf.lastModified().toString().toLatin1().data(), fiPng.lastModified().toString().toLatin1().data());
            if (fiPng.lastModified() > fiDxf.lastModified()) {
                RS_DEBUG->print("QG_LibraryWidget::getPathToPixmap: thumbnail found: '%s'",
                                pngPath.toLatin1().data());
                return pngPath;
            } else {
                RS_DEBUG->print("QG_LibraryWidget::getPathToPixmap: thumbnail needs to be updated: '%s'",
                                pngPath.toLatin1().data());
            }
        }
    }

    // create all directories needed:
    RS_SYSTEM->createPaths(iconCacheLocation + dir);

//    QString foo=iconCacheLocation + dir + QDir::separator() + fiDxf.baseName() + ".png";
    pngPath = iconCacheLocation + dir + QDir::separator() + fiDxf.baseName() + ".png";

    QPixmap* buffer = new QPixmap(128,128);
    RS_PainterQt painter(buffer);
    painter.setBackground(RS_Color(255,255,255));
    painter.eraseRect(0,0, 128,128);

    RS_StaticGraphicView gv(128,128, &painter);
    RS_Graphic graphic;
    if (graphic.open(dxfPath, RS2::FormatUnknown)) {
        gv.setContainer(&graphic);
        gv.zoomAuto(false);
        // gv.drawEntity(&graphic, true);

        for (RS_Entity* e=graphic.firstEntity(RS2::ResolveAll);
                e; e=graphic.nextEntity(RS2::ResolveAll)) {
            if (e->rtti() != RS2::EntityHatch){
                RS_Pen pen = e->getPen();
                pen.setColor(Qt::black);
                e->setPen(pen);
            }
            gv.drawEntity(&painter, e);
        }

        QImageWriter iio;
        QImage img;
        img = buffer->toImage();
        img = img.scaled(64,64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation );
        // iio.setImage(img);
        iio.setFileName(pngPath);
        iio.setFormat("PNG");
        if (!iio.write(img)) {
            pngPath = "";
            RS_DEBUG->print(RS_Debug::D_ERROR,
                            "QG_LibraryWidget::getPathToPixmap: Cannot write thumbnail: '%s'",
                            pngPath.toLatin1().data());
        }
    } else {
        RS_DEBUG->print(RS_Debug::D_ERROR,
                        "QG_LibraryWidget::getPathToPixmap: Cannot open file: '%s'",
                        dxfPath.toLatin1().data());
    }

    // GraphicView deletes painter
    painter.end();
    delete buffer;

    return pngPath;
}
QImage* nlm_filter(QImage* image, QSize size, int d, int ld, double sigma) {
    int pW = size.width()+d-(d%2!=0?1:0);
    int pH = size.height()+d-(d%2!=0?1:0);

    QImage* imageFiltered = new QImage(pW, pH, QImage::Format_RGB32);
    QImage* tmpImage1 = new QImage(pW, pH, QImage::Format_RGB32);

    nlm_increse_image(image, imageFiltered, size, d);


    double** redArray = new double*[pW];
    double** greenArray = new double*[pW];
    double** blueArray = new double*[pW];

    double** redArrayOutput = new double*[pW];
    double** greenArrayOutput = new double*[pW];
    double** blueArrayOutput = new double*[pW];

    createColorArrays(redArray, greenArray, blueArray, imageFiltered, pW, pH);
    createColorArrays(redArrayOutput, greenArrayOutput, blueArrayOutput, tmpImage1, pW, pH);

#ifdef MTHREADING
    QFuture<void> prRed = QtConcurrent::run(
                processColorArray,
                redArray,
                redArrayOutput,
                FilterParam(QSize(pW, pH), d, ld, sigma)
                );
    QFuture<void> prGreen = QtConcurrent::run(
                processColorArray,
                greenArray,
                greenArrayOutput,
                FilterParam(QSize(pW, pH), d, ld, sigma)
                );
    QFuture<void> prBlue = QtConcurrent::run(
                processColorArray,
                blueArray,
                blueArrayOutput,
                FilterParam(QSize(pW, pH), d, ld, sigma)
                );
    prRed.waitForFinished();
    prGreen.waitForFinished();
    prBlue.waitForFinished();
#else
    processColorArray(redArray, redArrayOutput, FilterParam(QSize(pW, pH), d, ld, sigma));
    processColorArray(greenArray, greenArrayOutput, FilterParam(QSize(pW, pH), d, ld, sigma));
    processColorArray(blueArray, blueArrayOutput, FilterParam(QSize(pW, pH), d, ld, sigma));
#endif

    QImage* tmpImage = new QImage(size, QImage::Format_RGB32);
    createImageFromColors(redArrayOutput, greenArrayOutput, blueArrayOutput, tmpImage, pW, pH, d);

    deleteColorsArrays(redArray, greenArray, blueArray, pW);
    deleteColorsArrays(redArrayOutput, greenArrayOutput, blueArrayOutput, pW);

    QImageWriter* writer = new QImageWriter();
    writer->setFileName("tmp.png");
    writer->write(*tmpImage);

    delete tmpImage1;
    delete imageFiltered;

    return tmpImage;
}
Beispiel #14
0
int LoadImage::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg)
{
  if (pdata.isEmpty())
  {
    errMsg = TR("<font color=orange>The image %1 is empty.</font>")
                         .arg(_name);
    return -2;
  }

  QString encodeddata;
  if (DEBUG)
    qDebug("LoadImage::writeToDB(): image starts with %s",
           pdata.left(10).data());
  if (QString(pdata.left(pdata.indexOf("\n"))).contains(QRegExp("^\\s*begin \\d+ \\S+")))
  {
    if (DEBUG) qDebug("LoadImage::writeToDB() image is already uuencoded");
    encodeddata = pdata;
  }
  else
  {
    // there's just GOT to be a better way to do this
    QImageWriter imageIo;
    QBuffer      imageBuffer;

    imageBuffer.open(QIODevice::ReadWrite);
    imageIo.setDevice(&imageBuffer);
    imageIo.setFormat(_filename.right(_filename.size() -
                                      _filename.lastIndexOf(".") - 1).toAscii());
    if (DEBUG)
      qDebug("LoadImage::writeToDB() image has format %s",
             imageIo.format().data());
    QImage image;
    image.loadFromData(pdata);
    if (!imageIo.write(image))
    {
      errMsg = TR("<font color=orange>Error processing image %1: "
                           "<br>%2</font>")
                .arg(_name).arg(imageIo.errorString());
      return -3;
    }

    imageBuffer.close();
    encodeddata = QUUEncode(imageBuffer);
    if (DEBUG) qDebug("LoadImage::writeToDB() image was uuencoded: %s",
                      qPrintable(encodeddata.left(160)));
  }

  QSqlQuery select;
  QSqlQuery upsert;

  int imageid  = -1;
  int pkgheadid = -1;
  int pkgitemid = -1;
  if (pkgname.isEmpty())
    select.prepare(QString("SELECT image_id, -1, -1"
                           "  FROM %1image "
                           " WHERE (image_name=:name);")
                          .arg(_system ? "" : "pkg"));
  else
    select.prepare(_pkgitemQueryStr);
  select.bindValue(":name",    _name);
  select.bindValue(":pkgname", pkgname);
  select.bindValue(":grade",   _grade);
  select.bindValue(":type",    _pkgitemtype);
  select.exec();
  if(select.first())
  {
    imageid  = select.value(0).toInt();
    pkgheadid = select.value(1).toInt();
    pkgitemid = select.value(2).toInt();
  }
  else if (select.lastError().type() != QSqlError::NoError)
  {
    QSqlError err = select.lastError();
    errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
    return -5;
  }

  if (imageid >= 0)
    upsert.prepare(QString("UPDATE %1image "
                           "   SET image_data=:source,"
                           "       image_descrip=:notes "
                           " WHERE (image_id=:id); ")
                          .arg(_system ? "" : "pkg"));
  else
  {
    upsert.prepare("SELECT NEXTVAL('image_image_id_seq');");
    upsert.exec();
    if (upsert.first())
      imageid = upsert.value(0).toInt();
    else if (upsert.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = upsert.lastError();
      errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
      return -6;
    }

    upsert.prepare(QString("INSERT INTO %1image "
                           "(image_id, image_name, image_data, image_descrip) "
                           "VALUES (:id, :name, :source, :notes);")
                          .arg(_system ? "" : "pkg"));
  }

  upsert.bindValue(":id",      imageid);
  upsert.bindValue(":source",  encodeddata);
  upsert.bindValue(":notes",   _comment);
  upsert.bindValue(":name",    _name);

  if (!upsert.exec())
  {
    QSqlError err = upsert.lastError();
    errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
    return -7;
  }

  if (pkgheadid >= 0)
  {
    int tmp = upsertPkgItem(pkgitemid, pkgheadid, imageid, errMsg);
    if (tmp < 0)
      return tmp;
  }

  return imageid;
}
Beispiel #15
0
void River::generateImages(QVector<QImage> &images, QVector<QString> & stockNames,
                           QMutex &imageMutex, Statistics & stats)
{
    imageMutex.lock();
    #pragma omp parallel
    {

     #pragma omp for
        for(int imageIndex = 0; imageIndex < NUM_IMAGES; imageIndex++){
            QColor color("black");
            images[imageIndex].fill(color.rgb());
        }

        #pragma omp for
        for(int i = 0; i < p.getSize(); i++){
            if(!p.hasWater[i]) {
                continue;
            }

            int x = p.pxcor[i];
            int y = p.pycor[i];

            QColor macroColor = getHeatMapColor(p.macro[i], stats.avgMacro, stats.maxMacro);
            QColor phytoColor = getHeatMapColor(p.phyto[i], stats.avgPhyto, stats.maxPhyto);
            QColor herbivoreColor = getHeatMapColor(p.herbivore[i], stats.avgHerbivore, stats.maxHerbivore);
            QColor waterDecompColor = getHeatMapColor(p.waterdecomp[i], stats.avgWaterDecomp, stats.maxWaterDecomp);
            QColor sedDecompColor = getHeatMapColor(p.seddecomp[i], stats.avgSedDecomp, stats.maxSedDecomp);
            QColor sedConsumerColor = getHeatMapColor(p.sedconsumer[i], stats.avgSedConsumer, stats.maxSedConsumer);
            QColor consumColor = getHeatMapColor(p.consumer[i], stats.avgConsum, stats.maxConsum);
            QColor DOCColor = getHeatMapColor(p.DOC[i], stats.avgDOC, stats.maxDOC);
            QColor POCColor = getHeatMapColor(p.POC[i], stats.avgPOC, stats.maxPOC);
            QColor detritusColor = getHeatMapColor(p.detritus[i], stats.avgDetritus, stats.maxDetritus);

            images[STOCK_MACRO].setPixel( x, y, macroColor.rgb());
            images[STOCK_PHYTO].setPixel(x, y, phytoColor.rgb());
            images[STOCK_HERBIVORE].setPixel(x, y, herbivoreColor.rgb());
            images[STOCK_WATERDECOMP].setPixel( x, y, waterDecompColor.rgb());
            images[STOCK_SEDDECOMP].setPixel(x, y, sedDecompColor.rgb());
            images[STOCK_SEDCONSUMER].setPixel(x, y, sedConsumerColor.rgb());
            images[STOCK_CONSUMER].setPixel(x, y, consumColor.rgb());
            images[STOCK_DOC].setPixel(x, y, DOCColor.rgb());
            images[STOCK_POC].setPixel(x, y, POCColor.rgb());
            images[STOCK_DETRITUS].setPixel(x, y, detritusColor.rgb());

            int patchCarbon = p.macro[i] + p.phyto[i] + p.herbivore[i] + p.waterdecomp[i] + p.seddecomp[i]
                    + p.sedconsumer[i] + p.consumer[i] + p.DOC[i] + p.POC[i] + p.detritus[i];
            QColor allCarbonColor = getHeatMapColor(patchCarbon, stats.avgCarbon, stats.maxCarbon);
            images[STOCK_ALL_CARBON].setPixel(x, y, allCarbonColor.rgb());
        }

        //Due to the layout of the hydrofiles, the river will appear upside down if we don't flip it.
        #pragma omp for
        for(int imageIndex = 0; imageIndex < NUM_IMAGES; imageIndex++){
            images[imageIndex] = images[imageIndex].mirrored(false,true);
        }
    }
    imageMutex.unlock();


    QImageWriter writer;
    writer.setFormat("png");
    for(int i = 0; i < NUM_IMAGES; i++){
        QString date_time_str = QDateTime::currentDateTime().toString("_MMM_d_H_mm_ss");
        QString fileName = "./results/images/" + stockNames[i] + date_time_str + ".png";
        writer.setFileName(fileName);
        writer.write(images[i]);
    }
}
Beispiel #16
0
//
// save image in the opengl texture into file
//
bool frag_pane::saveImage( const QString strFile )
{
   bool bRetCode = false;  
   QImageWriter writer;
   int nWidth, nHeight;
   int k, iRow, i, j, iRed, iGreen, iBlue;   
   QImage *img = NULL;
   GLubyte *image = NULL;
   
   if( !validImageProc( ) ) {
      goto PIX_EXIT;
   }
      
   if( !_out_fbo ) { 
      goto PIX_EXIT;
   }

   nWidth = _out_fbo->size().width( ); 
   nHeight = _out_fbo->size().height( ); 

   // get the buffer into texture
   
   _out_fbo->bind( );  

   glEnable( GL_TEXTURE_2D );    
   glViewport( 0, 0, nWidth, nHeight );
   
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();    

	glOrtho( 0.0, nWidth, 0.0, nHeight, -1.0, 1.0 );
   
   glMatrixMode( GL_MODELVIEW );
   glLoadIdentity( );
  
   glBindTexture( GL_TEXTURE_2D, _out_fbo->texture( ) ); 
            
   image = new GLubyte[nHeight*nWidth*4];
   if( !image ) {
      qDebug() << "ERROR! Memory Allocation Failed.";
      goto PIX_EXIT;
   }

   glReadPixels( 0, 0, nWidth, nHeight, GL_RGB, GL_UNSIGNED_BYTE, 
      image );
   
   // *** create image ***

   img = new QImage( nWidth, nHeight, QImage::Format_RGB888 );
   if( !img ) {
      qDebug() << "ERROR! Failed to Create QImage.";
      goto PIX_EXIT;
   }
   
   for( i = 0; i < nHeight; i++ ) {
      iRow = nHeight - i - 1;
      for( j = 0 ; j < nWidth ; j++ ) {
         k = i * nWidth + j;
         iRed = (int)image[k*3];
         iGreen = (int)image[k*3+1];
         iBlue = (int)image[k*3+2];
         img->setPixel( j, iRow, qRgb( iRed, iGreen, iBlue ) );
      }
   }
   
   // save the image

   writer.setFileName( strFile );   
   if( !writer.canWrite( ) ) {
      qDebug() << "ERROR! Can't write to this file " << strFile;
      goto PIX_EXIT;
    }
   
   if( !writer.write( *img ) ) {
      qDebug() << "ERROR! Failed to read image " << strFile;
      goto PIX_EXIT;
   }
   
   _out_fbo->release( ); 

   // --- DONE ---
   bRetCode = true;
PIX_EXIT:
   if( image ) {
      delete[] image;
      image = NULL;
   }
   if( img ) {
      delete img;
      img = NULL;
   }
   return bRetCode;
}
Beispiel #17
0
int LoadImage::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg)
{
  if (pdata.isEmpty())
  {
    errMsg = TR("<font color=orange>The image %1 is empty.</font>")
                         .arg(_name);
    return -2;
  }

  QByteArray encodeddata;
  if (DEBUG)
    qDebug("LoadImage::writeToDB(): image starts with %s",
           pdata.left(10).data());
  if (QString(pdata.left(pdata.indexOf("\n"))).contains(QRegExp("^\\s*begin \\d+ \\S+")))
  {
    if (DEBUG) qDebug("LoadImage::writeToDB() image is already uuencoded");
    encodeddata = pdata;
  }
  else
  {
    // there's just GOT to be a better way to do this
    QImageWriter imageIo;
    QBuffer      imageBuffer;

    imageBuffer.open(QIODevice::ReadWrite);
    imageIo.setDevice(&imageBuffer);
    imageIo.setFormat(_filename.right(_filename.size() -
                                      _filename.lastIndexOf(".") - 1).toAscii());
    if (DEBUG)
      qDebug("LoadImage::writeToDB() image has format %s",
             imageIo.format().data());
    QImage image;
    image.loadFromData(pdata);
    if (!imageIo.write(image))
    {
      errMsg = TR("<font color=orange>Error processing image %1: "
                           "<br>%2</font>")
                .arg(_name).arg(imageIo.errorString());
      return -3;
    }

    imageBuffer.close();
    encodeddata = QUUEncode(imageBuffer).toAscii();
    if (DEBUG) qDebug("LoadImage::writeToDB() image was uuencoded: %s",
                      encodeddata.left(160).data());
  }

  _selectMql = new MetaSQLQuery("SELECT image_id, -1, -1"
                      "  FROM <? literal(\"tablename\") ?> "
                      " WHERE (image_name=<? value(\"name\") ?>);");

  _updateMql = new MetaSQLQuery("UPDATE <? literal(\"tablename\") ?> "
                      "   SET image_data=<? value(\"source\") ?>,"
                      "       image_descrip=<? value(\"notes\") ?> "
                      " WHERE (image_id=<? value(\"id\") ?>) "
                      "RETURNING image_id AS id;");

  _insertMql = new MetaSQLQuery("INSERT INTO <? literal(\"tablename\") ?> ("
                      "   image_id, image_name, image_data, image_descrip"
                      ") VALUES ("
                      "  DEFAULT, <? value(\"name\") ?>,"
                      "  <? value(\"source\") ?>, <? value(\"notes\") ?>) "
                      "RETURNING image_id AS id;");

  ParameterList params;
  params.append("tablename", "image");

  return Loadable::writeToDB(encodeddata, pkgname, errMsg, params);
}
Beispiel #18
0
QVariant QXcbMime::mimeConvertToFormat(QXcbConnection *connection, xcb_atom_t a, const QByteArray &data, const QString &format,
                                       QVariant::Type requestedType, const QByteArray &encoding)
{
    QString atomName = mimeAtomToString(connection, a);
//    qDebug() << "mimeConvertDataToFormat" << format << atomName << data;

    if (!encoding.isEmpty()
        && atomName == format + QLatin1String(";charset=") + QString::fromLatin1(encoding)) {

#ifndef QT_NO_TEXTCODEC
        if (requestedType == QVariant::String) {
            QTextCodec *codec = QTextCodec::codecForName(encoding);
            if (codec)
                return codec->toUnicode(data);
        }
#endif

        return data;
    }

    // special cases for string types
    if (format == QLatin1String("text/plain")) {
        if (a == connection->atom(QXcbAtom::UTF8_STRING))
            return QString::fromUtf8(data);
        if (a == XCB_ATOM_STRING ||
            a == connection->atom(QXcbAtom::TEXT))
            return QString::fromLatin1(data);
    }

    // special case for uri types
    if (format == QLatin1String("text/uri-list")) {
        if (atomName == QLatin1String("text/x-moz-url")) {
            // we expect this as utf16 <url><space><title>
            // the first part is a url that should only contain ascci char
            // so it should be safe to check that the second char is 0
            // to verify that it is utf16
            if (data.size() > 1 && data.at(1) == 0)
                return QString::fromRawData((const QChar *)data.constData(),
                                data.size() / 2).split(QLatin1Char('\n')).first().toLatin1();
        }
    }

    if (atomName == format)
        return data;

#if 0 // ###
    // special case for images
    if (format == QLatin1String("image/ppm")) {
        if (a == XCB_ATOM_PIXMAP && data.size() == sizeof(Pixmap)) {
            Pixmap xpm = *((Pixmap*)data.data());
            if (!xpm)
                return QByteArray();
            Window root;
            int x;
            int y;
            uint width;
            uint height;
            uint border_width;
            uint depth;

            XGetGeometry(display, xpm, &root, &x, &y, &width, &height, &border_width, &depth);
            XImage *ximg = XGetImage(display,xpm,x,y,width,height,AllPlanes,depth==1 ? XYPixmap : ZPixmap);
            QImage qimg = QXlibStatic::qimageFromXImage(ximg);
            XDestroyImage(ximg);

            QImageWriter imageWriter;
            imageWriter.setFormat("PPMRAW");
            QBuffer buf;
            buf.open(QIODevice::WriteOnly);
            imageWriter.setDevice(&buf);
            imageWriter.write(qimg);
            return buf.buffer();
        }
    }
#endif
    return QVariant();
}