示例#1
0
QImage CursorTheme::autoCropImage(const QImage &image) const
{
    // Compute an autocrop rectangle for the image
    QRect r(image.rect().bottomRight(), image.rect().topLeft());
    const quint32 *pixels = reinterpret_cast<const quint32*>(image.bits());

    for (int y = 0; y < image.height(); y++)
    {
        for (int x = 0; x < image.width(); x++)
        {
            if (*(pixels++))
            {
                if (x < r.left())   r.setLeft(x);
                if (x > r.right())  r.setRight(x);
                if (y < r.top())    r.setTop(y);
                if (y > r.bottom()) r.setBottom(y);
            }
        }
    }

    // Normalize the rectangle
    return image.copy(r.normalized());
}
void 
MainWindow::LoadNewImage( QImage image )
///
/// Loads a new image
///
/// @param image
///  The image to be loaded
///
/// @return
///  Nothing
///
{
	// Move the past image to be the previous image
	if( mPreviousImage != NULL )
	{
		delete mPreviousImage;
	}

	mPreviousImage = mCurrentImage;

	// Delete next image if it exists, redo functionality will be reset.
	if( mNextImage != NULL )
	{
		delete mNextImage;
		mNextImage = NULL;
	}

	// Set this image as the current image
	mCurrentImage = new QImage();
	*mCurrentImage = image.copy();

	// Update the state of the GUI
	emit ImageLoaded( mCurrentImage != NULL && !mCurrentImage->isNull() );

	UpdateVisibleImage( image );
	UpdateEditMenuStates();
}
示例#3
0
void BarcodeQMLModel::scanningProcessMsg(){
    if (decThread->isRunning()) {return;}
    if (isActive){
        if (lastId == decThread->getLastSavedValue().id){
            if (result.size() < 12){
                setResult(result + " .");
            }else{
                setResult("");
            }
            QImage image = QtMainWindow::getView()->grabWindow();
            decThread->imageCaptured(image.copy(0, (image.height()-image.width())/2, image.width(), image.width()));
        }else{
            isActive = false;
            lastId = decThread->getLastSavedValue().id;
            setResult("Encoded format " + decThread->getLastSavedValue().format +
                      ": " + decThread->getLastSavedValue().result);

            //QSound::play(":/barcodesounds/scanner_sound.wav");

        }

        qDebug() << "scanningProcessMsg: " + result;
    }
}
示例#4
0
vector<QImage> EKGImageP::HSegmentation(QImage input)
{
    vector<ImageInfo> imageSum = getPicInfo(input);
    //Ghate ghate kardan Signal
    int start = 0,end = 0;
    vector<QImage> ghataat;
    bSignal = vector<double> (0);
    for(int row = 0 ; row < input.height() ; row++)
    {
        if(BlackPixel(imageSum[row]))
        {
            start = row;
            int Mmax = 0;
            while(BlackPixel(imageSum[row]) && row < input.height() )
            {
                if(imageSum[row].count > imageSum[Mmax].count)
                    Mmax = row;
                row++;
            }
            end = row - start;
            ghataat.push_back(input.copy(0,start,input.width(),end));
            maxCount.push_back(Mmax - start);
            //Check Vertical Count
            QImage imageBuffer = ghataat[ghataat.size()-1];
            vector<QImage> vseg = VSegmentation(imageBuffer);
            if (!HavaWidth(vseg ,imageBuffer.width() / 2))
            {
                ghataat.pop_back();
                maxCount.pop_back();
            }
        }
        end = 0;
    }
    //End Ghate ghate kardan Signal
    return ghataat;
}
示例#5
0
QImage CanvasModel::selectionToImage(int layerId) const
{
	QImage img;

	paintcore::Layer *layer = m_layerstack->getLayer(layerId);
	if(layer)
		img = layer->toImage();
	else
		img = toImage();


	if(m_selection) {
		img = img.copy(m_selection->boundingRect().intersected(QRect(0, 0, img.width(), img.height())));

		if(!m_selection->isAxisAlignedRectangle()) {
			// Mask out pixels outside the selection
			QPainter mp(&img);
			mp.setCompositionMode(QPainter::CompositionMode_DestinationIn);
			mp.drawImage(0, 0, m_selection->shapeMask(Qt::white));
		}
	}

	return img;
}
 QImage QtDistanceFieldFontTextureGenerator::crop(QRect &cropExtents, DistanceFieldGLFont::FontMetrics metrics, const QImage &image)
 {
     // Check to see that we won't crop out the logical origin
     int deltaX = cropExtents.x() - metrics.logical_origin.x();
     if (deltaX > 0)
     {
         cropExtents.setX(cropExtents.x() - deltaX);
         cropExtents.setWidth(cropExtents.width() + deltaX);
     }
     int deltaY = cropExtents.y() - metrics.logical_origin.y();
     if (deltaY > 0)
     {
         cropExtents.setY(cropExtents.y() - deltaY);
         cropExtents.setHeight(cropExtents.height() + deltaY);
     }
     LOGD << "Cropping";
     // Adjust the logical origin of metrics
     metrics.logical_origin.set(metrics.logical_origin.x() - cropExtents.x(), metrics.logical_origin.y() - cropExtents.y());
     // Adjust the width and height of metrics
     metrics.span.set(cropExtents.width(), cropExtents.height());
     // crop the image
     QImage croppedImage = image.copy(cropExtents);
     return croppedImage;
 }
bool Database::updateFaces(QList<Face>& faces, const QImage& ImageToTld) const
{
    Tlddatabase* const tlddatabase = new Tlddatabase();

    foreach(Face face, faces)
    {
        if(face.name() != NULL)
        {
            QImage faceToTld                = ImageToTld.copy(face.toFace().getX1(),face.toFace().getY1(),
                                                              face.toFace().getWidth(),face.toFace().getHeight());
            IplImage * const tmpface = tlddatabase->QImage2IplImage(faceToTld);
            IplImage* const inputfaceimage = cvCreateImage(cvSize(47,47),tmpface->depth,tmpface->nChannels);
            cvResize(tmpface,inputfaceimage);
            Tldrecognition* const tmpTLD    = new Tldrecognition;
            unitFaceModel *facemodeltostore = tmpTLD->getModeltoStore(inputfaceimage);
            facemodeltostore->Name          = face.name();
            tlddatabase->insertFaceModel(facemodeltostore);
            delete tmpTLD;
        }
    }

    delete tlddatabase;
    return true;
}
示例#8
0
void Fenetre::ClickTrouver()
{
  QImage img;
  int i;
  p_coord p=list_portees;
  
  list_images = NULL;
  
  img = Picture.copy();
  
  for (i=1; i<=largeur_ligne;i++)
    Dilater(&img);
  
  for (i=1; i<=largeur_ligne;i++)
  Eroder(&img);

  if (list_portees)
  list_images =TrouverMorceaux(&(img.copy(list_portees->pos)),espacement_ligne);
   
  ALabel->show();
  ALabel->resize(180, 150);
  ALabel->move(360, 340);
  ALabel->setPixmap(NULL);
}
extern "C" void gxpport_createimmutable_from_mutableregion
(gxpport_mutableimage_native_handle srcMutableImagePtr,
 int src_x, int src_y, 
 int src_width, int src_height,
 int transform,
 gxpport_image_native_handle* newImmutableImagePtr,
 gxutl_native_image_error_codes* creationErrorPtr) {

    QPixmap *srcqpixmap =
    gxpportqt_get_mutableimage_pixmap(srcMutableImagePtr);

    int rscSize = ImgRegionRscSize(srcqpixmap, src_width, src_height);

    /* Check resource limit */
    if (midpCheckResourceLimit(RSC_TYPE_IMAGE_IMMUT, rscSize) == 0) {
        /* Exceed Resource limit */
        *creationErrorPtr = GXUTL_NATIVE_IMAGE_RESOURCE_LIMIT;
        return;
    }

    QImage srcQImage = srcqpixmap->convertToImage();
    if (srcQImage.isNull()) {
        *creationErrorPtr = GXUTL_NATIVE_IMAGE_OUT_OF_MEMORY_ERROR;
        return;
    }

    _Platform_ImmutableImage* immutableImage = 
      (_Platform_ImmutableImage*)midpMalloc(sizeof(_Platform_ImmutableImage));
    if (immutableImage == NULL) {
	*creationErrorPtr = GXUTL_NATIVE_IMAGE_OUT_OF_MEMORY_ERROR;
	return;
    }

    immutableImage->qimage = new QImage(srcQImage.copy(src_x,
                                                       src_y, 
                                                       src_width, 
                                                       src_height));
    if (NULL == immutableImage->qimage) {
	midpFree(immutableImage);
        *creationErrorPtr = GXUTL_NATIVE_IMAGE_OUT_OF_MEMORY_ERROR;
        return;
    }

    if (immutableImage->qimage->isNull()) {
        delete immutableImage->qimage;
	midpFree(immutableImage);
        *creationErrorPtr = GXUTL_NATIVE_IMAGE_OUT_OF_MEMORY_ERROR;
        return;
    }

    if (transform != 0) {
        transform_image(immutableImage->qimage, transform);
    }

    /* Copy succeeds */
    if (midpIncResourceCount(RSC_TYPE_IMAGE_IMMUT, rscSize) == 0) {
        REPORT_ERROR(LC_LOWUI, "Error in updating resource limit"
                     " for Immutable image");
    }

    immutableImage->marker = 3;
    immutableImage->qpixmap = NULL;
    
    *newImmutableImagePtr = immutableImage;
    *creationErrorPtr = GXUTL_NATIVE_IMAGE_NO_ERROR;
}
示例#10
0
/*!
  \brief Draw the raster data
  \param painter Painter
  \param xMap X-Scale Map
  \param yMap Y-Scale Map
  \param canvasRect Contents rectangle of the plot canvas
*/
void QwtPlotRasterItem::draw( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect ) const
{
    if ( canvasRect.isEmpty() || d_data->alpha == 0 )
        return;

    const bool doCache = qwtUseCache( d_data->cache.policy, painter );

    const QwtInterval xInterval = interval( Qt::XAxis );
    const QwtInterval yInterval = interval( Qt::YAxis );

    /*
        Scaling an image always results in a loss of
        precision/quality. So we always render the image in
        paint device resolution.
    */

    QwtScaleMap xxMap, yyMap;
    qwtTransformMaps( painter->transform(), xMap, yMap, xxMap, yyMap );

    QRectF paintRect = painter->transform().mapRect( canvasRect );
    QRectF area = QwtScaleMap::invTransform( xxMap, yyMap, paintRect );

    const QRectF br = boundingRect();
    if ( br.isValid() && !br.contains( area ) )
    {
        area &= br;
        if ( !area.isValid() )
            return;

        paintRect = QwtScaleMap::transform( xxMap, yyMap, area );
    }

    QRectF imageRect;
    QImage image;

    QRectF pixelRect = pixelHint(area);
    if ( !pixelRect.isEmpty() )
    {
        // pixel in target device resolution 
        const double dx = qAbs( xxMap.invTransform( 1 ) - xxMap.invTransform( 0 ) );
        const double dy = qAbs( yyMap.invTransform( 1 ) - yyMap.invTransform( 0 ) );

        if ( dx > pixelRect.width() && dy > pixelRect.height() )
        {
            /*
              When the resolution of the data pixels is higher than
              the resolution of the target device we render in
              target device resolution.
             */
            pixelRect = QRectF();
        }
    }

    if ( pixelRect.isEmpty() )
    {
        if ( QwtPainter::roundingAlignment( painter ) )
        {
            // we want to have maps, where the boundaries of
            // the aligned paint rectangle exactly match the area

            paintRect = qwtAlignRect(paintRect);
            qwtAdjustMaps(xxMap, yyMap, area, paintRect);
        }

        // When we have no information about position and size of
        // data pixels we render in resolution of the paint device.

        image = compose(xxMap, yyMap, 
            area, paintRect, paintRect.size().toSize(), doCache);
        if ( image.isNull() )
            return;

        // Remove pixels at the boundaries, when explicitly
        // excluded in the intervals

        imageRect = qwtStripRect(paintRect, area, 
            xxMap, yyMap, xInterval, yInterval);

        if ( imageRect != paintRect )
        {
            const QRect r( 
                qRound( imageRect.x() - paintRect.x()),
                qRound( imageRect.y() - paintRect.y() ),
                qRound( imageRect.width() ),
                qRound( imageRect.height() ) );
                
            image = image.copy(r);
        }   
    }
    else
    {
        if ( QwtPainter::roundingAlignment( painter ) )
            paintRect = qwtAlignRect(paintRect);

        // align the area to the data pixels
        QRectF imageArea = qwtExpandToPixels(area, pixelRect);

        if ( imageArea.right() == xInterval.maxValue() &&
            !( xInterval.borderFlags() & QwtInterval::ExcludeMaximum ) )
        {
            imageArea.adjust(0, 0, pixelRect.width(), 0);
        }
        if ( imageArea.bottom() == yInterval.maxValue() &&
            !( yInterval.borderFlags() & QwtInterval::ExcludeMaximum ) )
        {
            imageArea.adjust(0, 0, 0, pixelRect.height() );
        }

        QSize imageSize;
        imageSize.setWidth( qRound( imageArea.width() / pixelRect.width() ) );
        imageSize.setHeight( qRound( imageArea.height() / pixelRect.height() ) );
        image = compose(xxMap, yyMap, 
            imageArea, paintRect, imageSize, doCache );
        if ( image.isNull() )
            return;

        imageRect = qwtStripRect(paintRect, area, 
            xxMap, yyMap, xInterval, yInterval);

        if ( ( image.width() > 1 || image.height() > 1 ) &&
            testPaintAttribute( PaintInDeviceResolution ) )
        {
            // Because of rounding errors the pixels 
            // need to be expanded manually to rectangles of 
            // different sizes

            image = qwtExpandImage(image, xxMap, yyMap, 
                imageArea, area, paintRect, xInterval, yInterval );
        }
    }

    painter->save();
    painter->setWorldTransform( QTransform() );
    
    QwtPainter::drawImage( painter, imageRect, image );

    painter->restore();
}
示例#11
0
		/** Create a clipped version of the image
		 *  \param [in] x The amount to remove from the left
		 *  \param [in] y The amount to remove from the top
		 *  \param [in] width The width to include
		 *  \param [in] height The height to include
		 *  \return The clipped image */
		Image sub_image( int x, int y, int width, int height ) const{
			QSize newSize( std::min( x+width,  x+mask.width()  ) - x
			             , std::min( y+height, y+mask.height() ) - y );
			auto newMask = newSize.isNull() ? QImage() : mask.copy( x,y, newSize.width(), newSize.height() );
			return Image( pos+QPoint(x,y), img, newMask );
		}
示例#12
0
//Implementation of VB similar transparency function
QImage setAlphaMask_VB(QImage image, QImage mask)
{
    if(mask.isNull())
        return image;

    if(image.isNull())
        return image;

    bool isWhiteMask = true;

    QImage target;

    target = QImage(image.width(), image.height(), QImage::Format_ARGB32);
    target.fill(qRgb(128,128,128));

    QImage newmask = mask;
    target.convertToFormat(QImage::Format_ARGB32);

    if(target.size()!= newmask.size())
    {
        newmask = newmask.copy(0, 0, target.width(), target.height());
    }

    QImage alphaChannel = image.alphaChannel();

    //vbSrcAnd
    for(int y=0; y< image.height(); y++ )
        for(int x=0; x < image.width(); x++ )
        {
            QColor Dpix = QColor(target.pixel(x,y));
            QColor Spix = QColor(newmask.pixel(x,y));
            QColor Npix;

            Npix.setAlpha(255);
            Npix.setRed( Dpix.red() & Spix.red());
            Npix.setGreen( Dpix.green() & Spix.green());
            Npix.setBlue( Dpix.blue() & Spix.blue());
            target.setPixel(x, y, Npix.rgba());

            isWhiteMask &= ( (Spix.red()>240) //is almost White
                             &&(Spix.green()>240)
                             &&(Spix.blue()>240));

            int newAlpha = 255-((Spix.red() + Spix.green() + Spix.blue())/3);

            if( (Spix.red()>240) //is almost White
                            &&(Spix.green()>240)
                            &&(Spix.blue()>240))
            {
                newAlpha = 0;
            }

            alphaChannel.setPixel(x,y, newAlpha);
        }

    //vbSrcPaint
    for(int y=0; y< image.height(); y++ )
        for(int x=0; x < image.width(); x++ )
        {
            QColor Dpix = QColor(image.pixel(x,y));
            QColor Spix = QColor(target.pixel(x,y));
            QColor Npix;

            Npix.setAlpha(255);
            Npix.setRed( Dpix.red() | Spix.red());
            Npix.setGreen( Dpix.green() | Spix.green());
            Npix.setBlue( Dpix.blue() | Spix.blue());
            target.setPixel(x, y, Npix.rgba());

            //QColor curAlpha;
            int curAlpha = QColor(alphaChannel.pixel(x,y)).red();
            int newAlpha = curAlpha+((Dpix.red() + Dpix.green() + Dpix.blue())/3);

            if(newAlpha>255) newAlpha=255;
            alphaChannel.setPixel(x,y, newAlpha);
        }

    target.setAlphaChannel(alphaChannel);

    return target;
}
示例#13
0
void V4LOutput::processFrame()
{
	//qDebug() << "V4LOutput::frameReady: Downscaling video for transmission to "<<m_transmitSize;
	// To scale the video frame, first we must convert it to a QImage if its not already an image.
	// If we're lucky, it already is. Otherwise, we have to jump thru hoops to convert the byte 
	// array to a QImage then scale it.
	QImage image;
	if(!m_frame->image().isNull())
	{
		image = m_frame->image();
	}
	else
	{
		const QImage::Format imageFormat = QVideoFrame::imageFormatFromPixelFormat(m_frame->pixelFormat());
		
		if(imageFormat != QImage::Format_Invalid)
		{
			image = QImage(m_frame->pointer(),
				m_frame->size().width(),
				m_frame->size().height(),
				m_frame->size().width() *
					(imageFormat == QImage::Format_RGB16  ||
					 imageFormat == QImage::Format_RGB555 ||
					 imageFormat == QImage::Format_RGB444 ||
					 imageFormat == QImage::Format_ARGB4444_Premultiplied ? 2 :
					 imageFormat == QImage::Format_RGB888 ||
					 imageFormat == QImage::Format_RGB666 ||
					 imageFormat == QImage::Format_ARGB6666_Premultiplied ? 3 :
					 4),
				imageFormat);
				
			image = image.copy();
			//qDebug() << "Downscaled image from "<<image.byteCount()<<"bytes to "<<scaledImage.byteCount()<<"bytes, orig ptr len:"<<m_frame->pointerLength()<<", orig ptr:"<<m_frame->pointer();
		}
		else
		{
			qDebug() << "VideoFilter::frameImage: Unable to convert pixel format to image format, cannot scale frame. Pixel Format:"<<m_frame->pixelFormat();
		}
	}
	
// 	if(image.width()  != FRAME_WIDTH ||
// 	   image.height() != FRAME_HEIGHT)
// 	{
// 		image = image.scaled(FRAME_WIDTH,FRAME_HEIGHT,Qt::IgnoreAspectRatio);
// 	}
	
	if(image.format() != V4L_QIMAGE_FORMAT)
		image = image.convertToFormat(V4L_QIMAGE_FORMAT);
		
	// QImage and V4L's def of RGB24 differ in that they have the R & B bytes swapped compared to each other 
	// - so we swap them here to appear correct in output. 
	if(V4L_NATIVE_FORMAT == VIDEO_PALETTE_RGB24 &&
	   V4L_QIMAGE_FORMAT == QImage::Format_RGB888)
	{
		uchar  tmp;
		uchar *bits = image.scanLine(0);
		for(int i=0; i<image.byteCount(); i+=3)
		{
			tmp       = bits[i];
			bits[i]   = bits[i+2];
			bits[i+2] = tmp;
		}
	}
	
	if(write(m_v4lOutputDev, (const uchar*)image.bits(), image.byteCount()) != image.byteCount()) 
	{
		qDebug() << "V4LOutput::readFrame(): Error writing to "<<m_v4lOutputName<<" (bytes written does not match bytes requested), V4L error: " << strerror(errno); 
	}
	else
	{
		//qDebug() << "DVizSharedMemoryThread::readFrame(): Wrote "<<outImg.byteCount()<<" bytes to "<<V4L_OUTPUT;
	} 
	
}
示例#14
0
QImage* PostScriptDocument::renderPage(const int pageNum, const int dpiX, const int dpiY) {

  Q_UNUSED(dpiX);
  Q_UNUSED(dpiY);

  if ((pageNum < 0) || (pageNum >= p_pages.count())) return NULL;

  PostScriptDocumentPage page = p_pages[pageNum];
  /*int width = reqSize.width();
  int height = reqSize.height();
  double magnify = 1.0f;
  if (page.orientation() == QPrinter::Landscape) {
    magnify = qMax((double)height / (double)page.size().width(),
                   (double)width / (double)page.size().height());
  } else {
    magnify = qMax((double)width / (double)page.size().width(),
                   (double)height / (double)page.size().height());
  }*/

  SpectrePage *spage = spectre_document_get_page(p_internal_document, pageNum);

  SpectreRenderContext *renderContext = spectre_render_context_new();

  /*spectre_render_context_set_scale(renderContext, magnify, magnify);*/
  spectre_render_context_set_use_platform_fonts(renderContext, false);
  spectre_render_context_set_antialias_bits(renderContext, 4, 4);
  /* Do not use spectre_render_context_set_rotation makes some files not render correctly, e.g. bug210499.ps
   * so we basically do the rendering without any rotation and then rotate to the orientation as needed
   * spectre_render_context_set_rotation(m_renderContext, req.orientation);
   */

  unsigned char *data = NULL;
  int row_length = 0;

  spectre_page_render(spage, renderContext, &data, &row_length);

  if (spectre_page_status(spage) != SPECTRE_STATUS_SUCCESS) {
    kDebug() << "Failed to render page" << pageNum+1 << ". Spectre fail status:" << spectre_page_status(spage);
    return NULL;
  }

  int width = page.size().width();
  int height = page.size().height();

  kDebug() << "Size of page" << pageNum+1 << "to render: " << width << "x" << height;

  // Qt4 needs the missing alpha of QImage::Format_RGB32 to be 0xff
  if (data && data[3] != 0xff)
    for (int i = 3; i < row_length * height; i += 4)
      data[i] = 0xff;

  QImage image;

  if (row_length == width * 4) {
    image = QImage(data, width, height, QImage::Format_RGB32);
  } else {
    // In case this ends up beign very slow we can try with some memmove
    QImage aux(data, row_length / 4, height, QImage::Format_RGB32);
    image = QImage(aux.copy(0, 0, width, height));
  }

  /*if (page.reversePage()) {

    if (page.orientation() == QPrinter::Portrait) {
      QTransform m;
      m.rotate(180);
      image = image.transformed(m);
    } else if (page.orientation() == QPrinter::Landscape) {
      QTransform m;
      m.rotate(270);
      image = image.transformed(m);
    }

  } else {

    if (page.orientation() == QPrinter::Landscape) {
      QTransform m;
      m.rotate(90);
      image = image.transformed(m);
    }

  }*/

  QImage *result = new QImage(image.copy());

  if ((result->width() != width) || (result->height() != height)) {
    kWarning().nospace() << "Generated image does not match wanted size: "
                    << "[" << result->width() << "x" << result->height() << "] vs requested "
                    << "[" << width << "x" << height << "]";
    QImage aux = result->scaled(width, height);
    delete result;
    result = new QImage(aux);
  }

  spectre_page_free(spage);

  spectre_render_context_free(renderContext);

  return result;

}
示例#15
0
void ThemeDialog::renderPreview(QImage preview, const QRect& foreground, const Theme& theme)
{
	m_load_color = QtConcurrent::run(averageImage, theme.backgroundImage(), theme.backgroundColor());

	// Position preview text
	int padding = theme.foregroundPadding();
	int x = foreground.x() + padding;
	int y = foreground.y() + padding + theme.spacingAboveParagraph();
	int width = foreground.width() - (padding * 2);
	int height = foreground.height() - (padding * 2) - theme.spacingAboveParagraph();
	m_preview_text->setGeometry(x, y, width, height);

	// Set colors
	QColor text_color = theme.textColor();
	text_color.setAlpha(255);

	QPalette p = m_preview_text->palette();
	p.setBrush(QPalette::Base, preview.copy(x, y, width, height));
	p.setColor(QPalette::Text, text_color);
	p.setColor(QPalette::Highlight, text_color);
	p.setColor(QPalette::HighlightedText, (qGray(text_color.rgb()) > 127) ? Qt::black : Qt::white);
	m_preview_text->setPalette(p);

	// Set spacings
	int tab_width = theme.tabWidth();
	QTextBlockFormat block_format;
	block_format.setLineHeight(theme.lineSpacing(), (theme.lineSpacing() == 100) ? QTextBlockFormat::SingleHeight : QTextBlockFormat::ProportionalHeight);
	block_format.setTextIndent(tab_width * theme.indentFirstLine());
	block_format.setTopMargin(theme.spacingAboveParagraph());
	block_format.setBottomMargin(theme.spacingBelowParagraph());
	m_preview_text->textCursor().mergeBlockFormat(block_format);
	for (int i = 0, count = m_preview_text->document()->allFormats().count(); i < count; ++i) {
		QTextFormat& f = m_preview_text->document()->allFormats()[i];
		if (f.isBlockFormat()) {
			f.merge(block_format);
		}
	}
	m_preview_text->setTabStopWidth(tab_width);
	m_preview_text->document()->setIndentWidth(tab_width);

	// Set font
	m_preview_text->setFont(theme.textFont());

	// Render text
	m_preview_text->render(&preview, m_preview_text->pos());

	// Create zoomed text cutout
	int x2 = (x >= 24) ? (x - 24) : 0;
	int y2 = (y >= 24) ? (y - 24) : 0;
	QImage text_cutout = preview.copy(x2, y2, 162, 110);

	// Create preview icon
	m_preview_icon = QImage(":/shadow.png").convertToFormat(QImage::Format_ARGB32_Premultiplied);
	{
		QPainter painter(&m_preview_icon);
		painter.drawImage(9, 9, preview.scaled(240, 135, Qt::KeepAspectRatio, Qt::SmoothTransformation));
		painter.fillRect(20, 32, 85, 59, QColor(0, 0, 0, 32));
		painter.fillRect(21, 33, 83, 57, Qt::white);
		int x3 = (x >= 24) ? (x - 12 + theme.tabWidth()) : 12 + theme.tabWidth();
		int y3 = (y >= 24) ? (y - 6) : 0;
		painter.drawImage(22, 34, preview, x3, y3, 81, 55);
	}

	// Create preview pixmap
	preview = preview.scaled(480, 270, Qt::KeepAspectRatio, Qt::SmoothTransformation);
	{
		QPainter painter(&preview);
		painter.setPen(Qt::NoPen);
		painter.fillRect(22, 46, 170, 118, QColor(0, 0, 0, 32));
		painter.fillRect(24, 48, 166, 114, Qt::white);
		painter.drawImage(26, 50, text_cutout);
	}
	m_preview->setPixmap(QPixmap::fromImage(preview));
}
示例#16
0
QImage ImageHandler::extractQImage(QObject *imageObj, int offsetX, int offsetY, int width, int height)
{
    QImage img;
#if defined(QZXING_QML)
#if QT_VERSION >= 0x050000
    QQuickItem *item = qobject_cast<QQuickItem *>(imageObj);

    if (!item || !item->window()->isVisible()) {
        qWarning() << "ImageHandler: item is NULL";
        return QImage();
    }

    QTime timer;
    timer.start();
    QSharedPointer<QQuickItemGrabResult> result = item->grabToImage();
    pendingGrabbersLocker.lockForWrite();
    pendingGrabbers << result.data();
    pendingGrabbersLocker.unlock();

    connect(result.data(), &QQuickItemGrabResult::ready, this, &ImageHandler::imageGrabberReady);
    while (timer.elapsed() < 1000) {
        pendingGrabbersLocker.lockForRead();
        if (!pendingGrabbers.contains(result.data())) {
            pendingGrabbersLocker.unlock();
            break;
        }
        pendingGrabbersLocker.unlock();
        qApp->processEvents();
        QThread::yieldCurrentThread();
    }
    img = result->image();
#else // QT_VERSION >= 0x050000
    QGraphicsObject *item = qobject_cast<QGraphicsObject*>(imageObj);

    if (!item) {
        qWarning() << "ImageHandler: item is NULL";
        return QImage();
    }

    img = QImage(item->boundingRect().size().toSize(), QImage::Format_RGB32);
    img.fill(QColor(255, 255, 255).rgb());
    QPainter painter(&img);
    QStyleOptionGraphicsItem styleOption;
    item->paint(&painter, &styleOption);
#endif // QT_VERSION >= 0x050000
#else // defined(QZXING_QML)
    Q_UNUSED(imageObj);
#endif // defined(QZXING_QML)

    if (offsetX < 0)
        offsetX = 0;
    if (offsetY < 0)
        offsetY = 0;
    if (width < 0)
        width = 0;
    if (height < 0)
        height = 0;

    if (offsetX || offsetY || width || height)
        return img.copy(offsetX, offsetY, width, height);
    else
        return img;
}
示例#17
0
void QVGPixmapData::fromNativeType(void* pixmap, NativeType type)
{
    if (type == QPixmapData::SgImage && pixmap) {
#if defined(QT_SYMBIAN_SUPPORTS_SGIMAGE) && !defined(QT_NO_EGL)
        RSgImage *sgImage = reinterpret_cast<RSgImage*>(pixmap);

        destroyImages();
        prevSize = QSize();

        TInt err = 0;

        RSgDriver driver;
        err = driver.Open();
        if (err != KErrNone) {
            cleanup();
            return;
        }

        if (sgImage->IsNull()) {
            cleanup();
            driver.Close();
            return;
        }

        TSgImageInfo sgImageInfo;
        err = sgImage->GetInfo(sgImageInfo);
        if (err != KErrNone) {
            cleanup();
            driver.Close();
            return;
        }

        pfnVgCreateEGLImageTargetKHR vgCreateEGLImageTargetKHR = (pfnVgCreateEGLImageTargetKHR) eglGetProcAddress("vgCreateEGLImageTargetKHR");

        if (eglGetError() != EGL_SUCCESS || !(QEgl::hasExtension("EGL_KHR_image") || QEgl::hasExtension("EGL_KHR_image_pixmap")) || !vgCreateEGLImageTargetKHR) {
            cleanup();
            driver.Close();
            return;
        }

        const EGLint KEglImageAttribs[] = {EGL_IMAGE_PRESERVED_SYMBIAN, EGL_TRUE, EGL_NONE};
        EGLImageKHR eglImage = QEgl::eglCreateImageKHR(QEgl::display(),
                EGL_NO_CONTEXT,
                EGL_NATIVE_PIXMAP_KHR,
                (EGLClientBuffer)sgImage,
                (EGLint*)KEglImageAttribs);

        if (eglGetError() != EGL_SUCCESS) {
            cleanup();
            driver.Close();
            return;
        }

        vgImage = vgCreateEGLImageTargetKHR(eglImage);
        if (vgGetError() != VG_NO_ERROR) {
            cleanup();
            QEgl::eglDestroyImageKHR(QEgl::display(), eglImage);
            driver.Close();
            return;
        }

        w = sgImageInfo.iSizeInPixels.iWidth;
        h = sgImageInfo.iSizeInPixels.iHeight;
        d = 32; // We always use ARGB_Premultiplied for VG pixmaps.
        is_null = (w <= 0 || h <= 0);
        source = QImage();
        recreate = false;
        prevSize = QSize(w, h);
        setSerialNumber(++qt_vg_pixmap_serial);
        // release stuff
        QEgl::eglDestroyImageKHR(QEgl::display(), eglImage);
        driver.Close();
#endif
    } else if (type == QPixmapData::FbsBitmap) {
        CFbsBitmap *bitmap = reinterpret_cast<CFbsBitmap*>(pixmap);

        bool deleteSourceBitmap = false;

#ifdef Q_SYMBIAN_HAS_EXTENDED_BITMAP_TYPE

        // Rasterize extended bitmaps

        TUid extendedBitmapType = bitmap->ExtendedBitmapType();
        if (extendedBitmapType != KNullUid) {
            bitmap = createBlitCopy(bitmap);
            deleteSourceBitmap = true;
        }
#endif

        if (bitmap->IsCompressedInRAM()) {
            bitmap = createBlitCopy(bitmap);
            deleteSourceBitmap = true;
        }

        TDisplayMode displayMode = bitmap->DisplayMode();
        QImage::Format format = qt_TDisplayMode2Format(displayMode);

        TSize size = bitmap->SizeInPixels();

        bitmap->BeginDataAccess();
        uchar *bytes = (uchar*)bitmap->DataAddress();
        QImage img = QImage(bytes, size.iWidth, size.iHeight, format);
        img = img.copy();
        bitmap->EndDataAccess();

        if(displayMode == EGray2) {
            //Symbian thinks set pixels are white/transparent, Qt thinks they are foreground/solid
            //So invert mono bitmaps so that masks work correctly.
            img.invertPixels();
        } else if(displayMode == EColor16M) {
            img = img.rgbSwapped(); // EColor16M is BGR
        }

        fromImage(img, Qt::AutoColor);

        if(deleteSourceBitmap)
            delete bitmap;
    }
}
示例#18
0
/**
 * Loads the thumbnail from the metadata.
 * If no thumbnail is embedded, the whole image
 * is loaded and downsampled in a fast manner.
 * @param file the file to be loaded
 * @return QImage the loaded image. Null if no image
 * could be loaded at all.
 **/ 
QImage DkThumbNail::computeIntern(const QFileInfo file, const QSharedPointer<QByteArray> ba, 
								  int forceLoad, int maxThumbSize, int minThumbSize, 
								  bool rescale) {
	
	DkTimer dt;
	//qDebug() << "[thumb] file: " << file.absoluteFilePath();

	// see if we can read the thumbnail from the exif data
	QImage thumb;
	DkMetaDataT metaData;

	try {
		if (!ba || ba->isEmpty())
			metaData.readMetaData(file);
		else
			metaData.readMetaData(file, ba);

		// read the full image if we want to create new thumbnails
		if (forceLoad != force_save_thumb)
			thumb = metaData.getThumbnail();
	}
	catch(...) {
		// do nothing - we'll load the full file
	}
	removeBlackBorder(thumb);

	if (thumb.isNull() && forceLoad == force_exif_thumb)
		return QImage();

	bool exifThumb = !thumb.isNull();

	int orientation = metaData.getOrientation();
	int imgW = thumb.width();
	int imgH = thumb.height();
	int tS = minThumbSize;

	// as found at: http://olliwang.com/2010/01/30/creating-thumbnail-images-in-qt/
	QString filePath = (file.isSymLink()) ? file.symLinkTarget() : file.absoluteFilePath();
	QImageReader* imageReader;
	
	if (!ba || ba->isEmpty())
		imageReader = new QImageReader(filePath);
	else {
		QBuffer buffer;
		buffer.setData(ba->data());
		buffer.open(QIODevice::ReadOnly);
		imageReader = new QImageReader(&buffer, QFileInfo(filePath).suffix().toStdString().c_str());
		buffer.close();
	}

	if (thumb.isNull() || thumb.width() < tS && thumb.height() < tS) {

		imgW = imageReader->size().width();
		imgH = imageReader->size().height();	// locks the file!
	}
	//else if (!thumb.isNull())
	//	qDebug() << "EXIV thumb loaded: " << thumb.width() << " x " << thumb.height();
	
	if (rescale && (imgW > maxThumbSize || imgH > maxThumbSize)) {
		if (imgW > imgH) {
			imgH = (float)maxThumbSize / imgW * imgH;
			imgW = maxThumbSize;
		} 
		else if (imgW < imgH) {
			imgW = (float)maxThumbSize / imgH * imgW;
			imgH = maxThumbSize;
		}
		else {
			imgW = maxThumbSize;
			imgH = maxThumbSize;
		}
	}

	if (thumb.isNull() || thumb.width() < tS && thumb.height() < tS || forceLoad == force_full_thumb || forceLoad == force_save_thumb) {
		
		// flip size if the image is rotated by 90°
		if (metaData.isTiff() && abs(orientation) == 90) {
			int tmpW = imgW;
			imgW = imgH;
			imgH = tmpW;
			qDebug() << "EXIV size is flipped...";
		}

		QSize initialSize = imageReader->size();

		imageReader->setScaledSize(QSize(imgW, imgH));
		thumb = imageReader->read();

		// try to read the image
		if (thumb.isNull()) {
			DkBasicLoader loader;
			
			if (loader.loadGeneral(file, ba, true, true))
				thumb = loader.image();
		}

		// the image is not scaled correctly yet
		if (rescale && !thumb.isNull() && (imgW == -1 || imgH == -1)) {
			imgW = thumb.width();
			imgH = thumb.height();

			if (imgW > maxThumbSize || imgH > maxThumbSize) {
				if (imgW > imgH) {
					imgH = (float)maxThumbSize / imgW * imgH;
					imgW = maxThumbSize;
				} 
				else if (imgW < imgH) {
					imgW = (float)maxThumbSize / imgH * imgW;
					imgH = maxThumbSize;
				}
				else {
					imgW = maxThumbSize;
					imgH = maxThumbSize;
				}
			}

			thumb = thumb.scaled(QSize(imgW*2, imgH*2), Qt::KeepAspectRatio, Qt::FastTransformation);
			thumb = thumb.scaled(QSize(imgW, imgH), Qt::KeepAspectRatio, Qt::SmoothTransformation);
		}

		// is there a nice solution to do so??
		imageReader->setFileName("josef");	// image reader locks the file -> but there should not be one so we just set it to another file...
		delete imageReader;

	}
	else if (rescale) {
		thumb = thumb.scaled(QSize(imgW, imgH), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
		//qDebug() << "thumb loaded from exif...";
	}

	if (orientation != -1 && orientation != 0 && (metaData.isJpg() || metaData.isRaw())) {
		QTransform rotationMatrix;
		rotationMatrix.rotate((double)orientation);
		thumb = thumb.transformed(rotationMatrix);
	}

	// save the thumbnail if the caller either forces it, or the save thumb is requested and the image did not have any before
	if (forceLoad == force_save_thumb || (forceLoad == save_thumb && !exifThumb)) {
		
		try {

			QImage sThumb = thumb.copy();
			if (orientation != -1 && orientation != 0) {
				QTransform rotationMatrix;
				rotationMatrix.rotate(-(double)orientation);
				sThumb = sThumb.transformed(rotationMatrix);
			}

			metaData.setThumbnail(sThumb);

			if (!ba || ba->isEmpty())
				metaData.saveMetaData(file);
			else
				metaData.saveMetaData(file, ba);

			qDebug() << "[thumb] saved to exif data";
		}
		catch(...) {
			qDebug() << "Sorry, I could not save the metadata";
		}
	}


	if (!thumb.isNull())
		qDebug() << "[thumb] " << file.fileName() << " loaded in: " << dt.getTotal() << ((exifThumb) ? " from EXIV" : " from File");

	//if (!thumb.isNull())
	//	qDebug() << "thumb: " << thumb.width() << " x " << thumb.height();


	return thumb;
}
void
get_transformed_pixmap(QPixmap* originalPixmap,
		       QPixmap* destPixmap,
		       int src_x, int src_y, 
		       int src_width, int src_height,
		       int transform,
		       bool hasAlpha) {

    QImage originalImage = originalPixmap->convertToImage();

    if ( hasAlpha ) {
	// Qt's handling of the alpha channel in the conversion
	// process between QPixmap and QImage is buggy.
	// If the pixmap's pixels only have alpha values 0x00 and 0xFF
	// then the resulting QImage from conversion will return
	// false for hasAlphaBuffer().
	// so we set our own flag instead of depending on Qt to 
	// maintain alpha information.
	originalImage.setAlphaBuffer(TRUE);
    }

    /*Qt gives us this useful API that returns a section of a QImage*/
    QImage sectionImage  = originalImage.copy(src_x, src_y, 
					      src_width, src_height);
    /* Skip this pixel-by-pixel copy if there is no transform */
    if (0 != transform) {
	QImage sectionImage32bpp = sectionImage.convertDepth(32);
	QImage processedImage;
	
	
	int nXOriginSrc = 0;
	int nYOriginSrc = 0;
	int nWidth      = src_width;
	int nHeight     = src_height;
	
	/*scan length of the source image*/
	int imageWidth  = src_width;
	/*number of rows of the source image*/
	int imageHeight = src_height;
	
	int imgLen;
	int srcImgLen;
	
	int t_width;
	int t_height;
	
	int srcX;
	int srcY;
	int xStart;
	int yStart;
	int xIncr;
	int yIncr;
	int destX;
	int destY;
	int yCounter;
	int xCounter;
	
	int srcIndex;
	int destIndex;
	
	uchar* srcBits     = NULL;
	uchar* destBits    = NULL;
	
	uchar* srcBitsPtr  = NULL;
	uchar* destBitsPtr = NULL;
	
	
	/* set dimensions of image being created,
	   depending on transform */
	if (transform & TRANSFORM_INVERTED_AXES) {
	    t_width  = src_height;
	    t_height = src_width;
	} else {
	    t_width  = src_width;
	    t_height = src_height;
	}
	
	/* width * height * 4 gives us the size of a 32 bpp image */
	imgLen = nWidth * nHeight << 2;
	srcImgLen = imageWidth  * imageHeight << 2;
	
	/* Qt specific */
	processedImage.create(t_width, t_height, 32);
	
	srcBits  = sectionImage32bpp.bits();
	destBits = processedImage.bits();
	/* ----------- */
	
	if (transform & TRANSFORM_Y_FLIP) {
	    yStart = nHeight-1;
	    yIncr = -1;
	} else {
	    yStart = 0;
	    yIncr = +1;
	}
	
	if (transform & TRANSFORM_X_FLIP) {
	    xStart = nWidth-1;
	    xIncr = -1;
	} else {
	    xStart = 0;
	    xIncr = +1;
	}
	
	srcBitsPtr  = srcBits;
	destBitsPtr = destBits;
	
	
	/* increment srcX,Y regular. increment destX,Y according to transform.
	   this makes handling of mask and alpha values easier */
	
	for (srcY = nYOriginSrc, destY = yStart, yCounter = 0; 
	     yCounter < nHeight; 
	     srcY++, destY+=yIncr, yCounter++) {
	    
	    /* in the current implementation we have source bitmap
	       dimension as the width of the image and the height of the region
	       destination bitmap is of the dimensions of the region */
	    
	    for (srcX = nXOriginSrc, destX = xStart, xCounter = 0; 
		 xCounter < nWidth; 
		 srcX++, destX+=xIncr, xCounter++) {
		
		if ( transform & TRANSFORM_INVERTED_AXES ) {
		    destIndex =  ( ( (destX) * t_width) + (destY) );
		} else {
		    destIndex =  ( ( (destY) * t_width) + (destX) );
		}
		
		destBitsPtr =  destBits + (destIndex * 4) ;
		
		srcIndex = (((srcY) * imageWidth) + (srcX));
		srcBitsPtr = srcBits + (srcIndex * 4);
		
		
		/* copy the pixel that is pointed to */
		*((int *)destBitsPtr) = *((int *)srcBitsPtr);
		
	    } /*for x*/
	    
	} /* for y */
	
	
	/* ---------- */

	if(TRUE == sectionImage.hasAlphaBuffer() ) {
	    processedImage.setAlphaBuffer(TRUE);
	} else {
	    processedImage.setAlphaBuffer(FALSE);
	}
	
	destPixmap->convertFromImage(processedImage);
    } else {
	/* No transform, just copy the image sub-section */
	destPixmap->convertFromImage(sectionImage);
    }
}
extern "C" void gxpport_decodeimmutable_from_argb
(jint* srcBuffer,
 int width, int height,
 jboolean processAlpha,
 gxpport_image_native_handle* newImmutableImagePtr,
 gxutl_native_image_error_codes* creationErrorPtr) {

    // use bytes as is, QT images have the same binary data layout
    QImage qimage = QImage((unsigned char*)srcBuffer, 
                           width, height, 
                           IMAGE_DEPTH,
                           NULL, 0, 
                           QImage::IgnoreEndian);

    if (qimage.isNull()) {
        *creationErrorPtr = GXUTL_NATIVE_IMAGE_DECODING_ERROR;
        return;
    }

    /* Check Resource limit */
    int rscSize = ImgRscSize(&qimage);

    if (midpCheckResourceLimit(RSC_TYPE_IMAGE_IMMUT, rscSize) == 0) {
        /* Exceed Resource limit */
        *creationErrorPtr = GXUTL_NATIVE_IMAGE_RESOURCE_LIMIT;
        return;
    }

    qimage.setAlphaBuffer(processAlpha == KNI_TRUE?TRUE:FALSE);

    _Platform_ImmutableImage* immutableImage =
        (_Platform_ImmutableImage*)midpMalloc(sizeof(_Platform_ImmutableImage));
    if (immutableImage == NULL) {
        *creationErrorPtr = GXUTL_NATIVE_IMAGE_OUT_OF_MEMORY_ERROR;
        return;
    }

    // make a deep copy of the image
    immutableImage->qimage = new QImage(qimage.copy());
    if (NULL == immutableImage->qimage) {
	midpFree(immutableImage);
        *creationErrorPtr = GXUTL_NATIVE_IMAGE_OUT_OF_MEMORY_ERROR;
        return;
    }

    if (immutableImage->qimage->isNull()) {
        delete immutableImage->qimage;
	midpFree(immutableImage);
        *creationErrorPtr = GXUTL_NATIVE_IMAGE_OUT_OF_MEMORY_ERROR;
        return;
    }

    /* Image creation succeeds */
    if (midpIncResourceCount(RSC_TYPE_IMAGE_IMMUT, rscSize) == 0) {
        REPORT_ERROR(LC_LOWUI, "Error in updating "
                     "resource limit for Immutable image");
    }

    immutableImage->marker = 6;
    immutableImage->qpixmap = NULL;

    *newImmutableImagePtr = immutableImage;
    *creationErrorPtr = GXUTL_NATIVE_IMAGE_NO_ERROR;
}
CameraImageWrapper::CameraImageWrapper(const QImage &sourceImage) : LuminanceSource(sourceImage.width(), sourceImage.height())
{
    image = sourceImage.copy();
}
示例#22
0
void ThumbGenerator::run()
{
    RunProlog();

    m_cancel = false;
    while (moreWork() && !m_cancel)
    {
        QString file, dir;
        bool    isGallery;

        m_mutex.lock();
        dir       = m_directory;
        isGallery = m_isGallery;
        file = m_fileList.first();
        if (!m_fileList.isEmpty())
            m_fileList.pop_front();
        m_mutex.unlock();
        if (file.isEmpty())
            continue;

        QString   filePath = dir + QString("/") + file;
        QFileInfo fileInfo(filePath);
        if (!fileInfo.exists())
            continue;

        if (isGallery)
        {
            if (fileInfo.isDir())
                isGallery = checkGalleryDir(fileInfo);
            else
                isGallery = checkGalleryFile(fileInfo);
        }

        if (!isGallery)
        {
            QString cachePath = QString("%1%2.jpg").arg(getThumbcacheDir(dir))
                                                   .arg(file);
            QFileInfo cacheInfo(cachePath);

            if (cacheInfo.exists() &&
                cacheInfo.lastModified() >= fileInfo.lastModified())
            {
                continue;
            }
            else
            {
                // cached thumbnail not there or out of date
                QImage image;

                // Remove the old one if it exists
                if (cacheInfo.exists())
                    QFile::remove(cachePath);

                if (fileInfo.isDir())
                    loadDir(image, fileInfo);
                else
                    loadFile(image, fileInfo);

                if (image.isNull())
                    continue; // give up;

                // if the file is a movie save the image to use as a screenshot
                if (GalleryUtil::IsMovie(fileInfo.filePath()))
                {
                    QString screenshotPath = QString("%1%2-screenshot.jpg")
                            .arg(getThumbcacheDir(dir))
                            .arg(file);
                    image.save(screenshotPath, "JPEG", 95);
                }

                image = image.scaled(m_width,m_height,
                                Qt::KeepAspectRatio, Qt::SmoothTransformation);
                image.save(cachePath, "JPEG", 95);

                // deep copies all over
                ThumbData *td = new ThumbData;
                td->directory = dir;
                td->fileName  = file;
                td->thumb     = image.copy();

                // inform parent we have thumbnail ready for it
                QApplication::postEvent(m_parent, new ThumbGenEvent(td));

            }
        }
    }

    RunEpilog();
}
示例#23
0
XCursorImage::XCursorImage (const QString &aName, const QImage &aImg, int aXHot, int aYHot, quint32 aDelay, quint32 aCSize) :
  mIsValid(true), mName(aName), mImage(0), mDelay(aDelay), mXHot(aXHot), mYHot(aYHot), mCSize(aCSize)
{
  mImage = new QImage(aImg.copy());
  convertARGB2PreMul(*mImage);
}
示例#24
0
QString Executor::cardFromImage(QImage & img)
{
   QImage im(img);
   toBlackWhiteMid(im, 128);

   const int w = im.width();
   const int h = im.height();
   int y_split = 0;
   //поиск первой черной полосы
   int y_black = 0;
   for (int y = 1; y < h; ++y)
   {
      for (int x = 0; x < w; ++x)
      {
         if (im.pixel(x, y) == qRgb(0, 0, 0))
         {
            y_black = y;
            y = h;
            break;
         }
      }
   }
   //поиск первой белой полосы
   for (int y = y_black; y < h; ++y)
   {
      int cnt_wt = 0;
      for (int x = 0; x < w; ++x)
      {
         if (im.pixel(x, y) == qRgb(255, 255, 255))
         {
            cnt_wt++;
         }
         else
         {
            break;
         }
      }
      if (cnt_wt == w)
      {
         y_split = y;
         break;
      }
   }
   //обжимаем картинки слева и справа
   QImage imc  = im.copy(0, 1, w, y_split);
   
   int left_wt = 0;
   for (int x = 0; x < imc.width(); ++x)
   {
      for (int y = 0; y < imc.height(); ++y)
      {
         if (imc.pixel(x, y) != qRgb(255, 255, 255))
         {
            x = imc.width() + 1;
            break;
         }
      }
      if (x != imc.width() + 1)
         left_wt++;
   }

   int right_wt = 0;
   for (int x = imc.width() - 1; x > 0; --x)
   {
      for (int y = 0; y < imc.height(); ++y)
      {
         if (imc.pixel(x, y) != qRgb(255, 255, 255))
         {
            x = -1;
            break;
         }
      }
      if (x != -1)
         right_wt++;
   }

   QImage top  = img.copy(left_wt, 1, imc.width() - left_wt - right_wt, y_split);
   QImage topwb = im.copy(left_wt, 1, imc.width() - left_wt - right_wt, y_split);
   //topwb.save("../CardBase/RSP/split/" + fl + "_nm.bmp");
   //top.save("../CardBase/RSP/split/" + fl + "_nm1.bmp");

   CardOCR ocr;
   //подаем черно-белую
   QString card = ocr.nominal(&topwb) +
      ocr.suit(&topwb, &top);

   return card;
}
示例#25
0
void doMagicIn(QString path, QString q, QString OPath)
{
    QRegExp isMask = QRegExp("*m.gif");
    isMask.setPatternSyntax(QRegExp::Wildcard);

    QRegExp isBackupDir = QRegExp("*/_backup/");
    isBackupDir.setPatternSyntax(QRegExp::Wildcard);

    if(isBackupDir.exactMatch(path))
        return; //Skip backup directories

    if(isMask.exactMatch(q))
        return;

    QImage target;
    QString imgFileM;
    QStringList tmp = q.split(".", QString::SkipEmptyParts);
    if(tmp.size()==2)
        imgFileM = tmp[0] + "m." + tmp[1];
    else
        return;

    //skip unexists pairs
    if(!QFile(path+q).exists())
        return;

    if(!QFile(path+imgFileM).exists())
    {
        QString saveTo;

        QImage image = loadQImage(path+q);
        if(image.isNull()) return;

        QTextStream(stdout) << QString(path+q+"\n").toUtf8().data();

        saveTo = QString(OPath+(tmp[0].toLower())+".gif");
        //overwrite source image (convert BMP to GIF)
        if(toGif( image, saveTo ) ) //Write gif
        {
            QTextStream(stdout) <<"GIF-1 only\n";
        }
        else
        {
            QTextStream(stdout) <<"BMP-1 only\n";
            image.save(saveTo, "BMP"); //If failed, write BMP
        }
        return;
    }

    if(!noBackUp)
    {
        //create backup dir
        QDir backup(path+"_backup/");
        if(!backup.exists())
        {
            QTextStream(stdout) << QString("Create backup with path %1\n").arg(path+"_backup");
            if(!backup.mkdir("."))
                QTextStream(stderr) << QString("WARNING! Can't create backup directory %1\n").arg(path+"_backup");

        }

        //create Back UP of source images
        if(!QFile(path+"_backup/"+q).exists())
            QFile::copy(path+q, path+"_backup/"+q);
        if(!QFile(path+"_backup/"+imgFileM).exists())
            QFile::copy(path+imgFileM, path+"_backup/"+imgFileM);
    }

    QImage image = loadQImage(path+q);
    QImage mask = loadQImage(path+imgFileM);

    if(mask.isNull()) //Skip null masks
        return;

    target = setAlphaMask(image, mask);

    if(!target.isNull())
    {
        //Save before fix
        //target.save(OPath+tmp[0]+"_before.png");
        //mask.save(OPath+tmp[0]+"_mask_before.png");
        QTextStream(stdout) << QString(path+q+"\n").toUtf8().data();

        //fix
        if(image.size()!= mask.size())
            mask = mask.copy(0,0, image.width(), image.height());

        mask = target.alphaChannel();
        mask.invertPixels();

        //Save after fix
        //target.save(OPath+tmp[0]+"_after.bmp", "BMP");
        QString saveTo;


        saveTo = QString(OPath+(tmp[0].toLower())+".gif");

        //overwrite source image (convert BMP to GIF)
        if(toGif(image, saveTo ) ) //Write gif
        {
            QTextStream(stdout) <<"GIF-1 ";
        }
        else
        {
            QTextStream(stdout) <<"BMP-1 ";
            image.save(saveTo, "BMP"); //If failed, write BMP
        }

        saveTo = QString(OPath+(tmp[0].toLower())+"m.gif");

        //overwrite mask image
        if( toGif(mask, saveTo ) ) //Write gif
        {
            QTextStream(stdout) <<"GIF-2\n";
        }
        else
        {
            mask.save(saveTo, "BMP"); //If failed, write BMP
            QTextStream(stdout) <<"BMP-2\n";
        }
    }
    else
        QTextStream(stderr) << path+q+" - WRONG!\n";
}
示例#26
0
void Executor::timerEvent(QTimerEvent *)
{
   TimerKiller killer(this, timer_id_, interval_);
   //ищем топовое окно заданного класса
   static const QString psClass = "TfrmTable";
   static const int minFoldHue = 15;
   static const int maxFoldHue = 30;
   static const int minCallHue = 60;
   static const int maxCallHue = 70;
   static const int minCheckHue = 42;
   static const int maxCheckHue = 58;

   //смотрим топовое окно
   WId FgWnd = GetForegroundWindow();
   char clName[MAX_WND_TEXT];
   GetClassNameA(FgWnd, clName, MAX_WND_TEXT);
   QString sClass(clName);
   if (!sClass.contains(psClass))
   {
      return;
   }

   //область кнопок
   QRect checkRect;
   QRect foldRect;
   bool hasCheck = false;
   bool hasFold  = false;
   bool hasCall  = false;

   int btnHeight = 110;
   int btnWidth = 0;
   WId BtnWnd = FindWindowEx(FgWnd, NULL, L"TAniLayer", NULL); 
   if (BtnWnd)
   {
      RECT btnRect;
      //GetClientRect(BtnWnd, &btnRect);
      GetWindowRect(BtnWnd, &btnRect);
      btnHeight = btnRect.bottom - btnRect.top;
      btnWidth = btnRect.right - btnRect.left;
      btnWidth = btnWidth >> 1;
      HwndToTop(FgWnd);

      //делаем скрин области кнопок
      QPixmap pixBtn = QPixmap::grabWindow(BtnWnd, btnWidth, 0, btnWidth, btnHeight);
      QImage imgBtn  = pixBtn.toImage();
      //imgBtn.save("btn.bmp");
      
      QPoint ptFold, ptCall, ptCheck;
      //здесь нужна обработка нашего хода
      static const int rectMin = 10;
      //Начинаем поиск с кнопки Чек
      //если она есть то однозначно наш ход
      hasCheck = Proc770::checkHueButton(imgBtn, minCheckHue, maxCheckHue, 
         rectMin, checkRect);
      if (!hasCheck)
      {
         //ищем кнопку Fold и Call
         hasFold = Proc770::checkHueButton(imgBtn, minFoldHue, maxFoldHue, 
            rectMin, foldRect);
         hasCall = Proc770::checkHueButton(imgBtn, minCallHue, maxCallHue, rectMin);

         if (hasFold && hasCall)
         {
            //qDebug() << "FOLD is avail";
         }
         else
         {
            return;
         }
      }
      else
      {
         //qDebug() << "CHECK is avail";
      }
   }

   //здесь наш ход
   QPixmap pixRoom = QPixmap::grabWindow(FgWnd);
   QRect rectRoom = pixRoom.rect();
   rectRoom.setHeight(rectRoom.height() - btnHeight);
   QImage imgRoom = pixRoom.copy(rectRoom).toImage();
   
   // устанавливаем изображение для обработки
   cardProc_->setImage(imgRoom);
   // если стадия префлопа 
   if (cardProc_->isPreflop())
   {
      //qDebug() << "Preflop!";
      // получить карманные карты
      bool ok = false;
      QPair<QRect, QRect> holeCards = cardProc_->getHoleCards(&ok);
      if (!ok)
         return;

      /// Debugging {
      //uint num = 0;
      //num = QDateTime::currentDateTime().toTime_t();
      //imgRoom.save(QString("test/table_%1.bmp").arg(num));
      //imgBtn.save(QString("test/btns_%1.bmp").arg(num));
      //imgRoom.copy(holeCards.first).save(QString("test/first_%1.bmp").arg(num));
      //imgRoom.copy(holeCards.second).save(QString("test/second_%1.bmp").arg(num));
      /// } Debugging

      if (holeCards.first.isEmpty() || holeCards.second.isEmpty() ||
          holeCards.first.isNull() || holeCards.second.isNull())
          return;

      QImage firstImg  = imgRoom.copy(holeCards.first);
      QImage secondImg = imgRoom.copy(holeCards.second);

      QString card1 = cardFromImage(firstImg);
      QString card2 = cardFromImage(secondImg);

      if (card1.length() != 2 || card2.length() != 2)
         return;

      //qDebug() << card1 << card2;
      
      //сохранить карты в кэш
      QString joined = card1 + card2;
      if (joined == cache_ && !lastIsFold_)
      {
         //хорошие карты - человек думает, не мешать
         return;
      } 
      else
      {
         cache_ = joined;
      }
      
      QString range = cardRangeFromHoles(card1, card2);
      //qDebug() << range;
      if (playingCard_.contains(range))
      {
         //panic!
         lastIsFold_ = false;
         if (data_.visualAlert)
         {
            alarm_->highlight(joined, FgWnd);
         }
         if (data_.turnBeep)
         {
            QString appExe = qApp->applicationDirPath();
            QSound::play(appExe + "/sounds/turn.wav");
         }
      }
      else
      {
         if (data_.advisorMode)
         {
            QString advice = tr("Fold/Check this hand: %1")
               .arg(card1 + " " + card2);
            cbFun(advice.toStdString().c_str());
            return;
         }
         
         //foldOrCheck(FgWnd);
         //qDebug() << "Check Rect" << checkRect;
         int w = checkRect.width();
         int h = checkRect.height();
         checkRect.setX(btnWidth + checkRect.x());
         checkRect.setY(imgRoom.height() + checkRect.y());
         checkRect.setWidth(w);
         checkRect.setHeight(h);
         //qDebug() << "New Check Rect" << checkRect;

         //qDebug() << "Fold Rect" << foldRect;
         w = foldRect.width();
         h = foldRect.height();
         foldRect.setX(btnWidth + foldRect.x());
         foldRect.setY(imgRoom.height() + foldRect.y());
         foldRect.setWidth(w);
         foldRect.setHeight(h);
         //qDebug() << "New Fold Rect" << foldRect;
         if (hasCheck)
         {
            if (data_.checkBeep)
            {
               QString appExe = qApp->applicationDirPath();
               QSound::play(appExe + "/sounds/check.wav");
            }
            
            clickTo(FgWnd, checkRect);
            
            if (data_.showFolded)
            {
               QString sAction = tr("This hand has been checked: ");
               cbFun(QString(sAction + card1 + " " + card2).toStdString().c_str());
            }

            //обнулить кэш
            cache_.clear();
            lastIsFold_ = false;
         }
         else if (hasFold)
         {
            lastIsFold_ = true;
            if (data_.foldBeep)
            {
               QString appExe = qApp->applicationDirPath();
               QSound::play(appExe + "/sounds/fold.wav");
            }

            clickTo(FgWnd, foldRect);
            
            if (data_.showFolded)
            {
               QString sAction = tr("This hand has been folded: ");
               cbFun(QString(sAction + card1 + " " + card2).toStdString().c_str());
            }
         }
      }
   }
//код для набивки базы карт
/*
   qDebug() << "Check Rect" << checkRect;
   int w = checkRect.width();
   int h = checkRect.height();
   checkRect.setX(btnWidth + checkRect.x());
   checkRect.setY(imgRoom.height() + checkRect.y());
   checkRect.setWidth(w);
   checkRect.setHeight(h);
   qDebug() << "New Check Rect" << checkRect;

   qDebug() << "Fold Rect" << foldRect;
   w = foldRect.width();
   h = foldRect.height();
   foldRect.setX(btnWidth + foldRect.x());
   foldRect.setY(imgRoom.height() + foldRect.y());
   foldRect.setWidth(w);
   foldRect.setHeight(h);
   qDebug() << "New Fold Rect" << foldRect;

   if (cardProc_->isPreflop())
   {
      if (hasCheck)
      {
         clickTo(FgWnd, checkRect);
      }
      else if (hasFold && hasCall)
      {
         clickTo(FgWnd, foldRect);
      }
   }
   else
   {
      clickTo(FgWnd, foldRect);
      clickTo(FgWnd, checkRect);

      qDebug() << "Flop at least!";
      return;
   }
*/
}
示例#27
0
gpu::Texture* TextureUsage::createCubeTextureFromImage(const QImage& srcImage, const std::string& srcImageName) {
    QImage image = srcImage;
    
    int imageArea = image.width() * image.height();
    
    
    qCDebug(modelLog) << "Cube map size:" << QString(srcImageName.c_str()) << image.width() << image.height();
    
    int opaquePixels = 0;
    int translucentPixels = 0;
    //bool isTransparent = false;
    int redTotal = 0, greenTotal = 0, blueTotal = 0, alphaTotal = 0;
    const int EIGHT_BIT_MAXIMUM = 255;
    QColor averageColor(EIGHT_BIT_MAXIMUM, EIGHT_BIT_MAXIMUM, EIGHT_BIT_MAXIMUM);
    
    if (!image.hasAlphaChannel()) {
        if (image.format() != QImage::Format_RGB888) {
            image = image.convertToFormat(QImage::Format_RGB888);
        }
        // int redTotal = 0, greenTotal = 0, blueTotal = 0;
        for (int y = 0; y < image.height(); y++) {
            for (int x = 0; x < image.width(); x++) {
                QRgb rgb = image.pixel(x, y);
                redTotal += qRed(rgb);
                greenTotal += qGreen(rgb);
                blueTotal += qBlue(rgb);
            }
        }
        if (imageArea > 0) {
            averageColor.setRgb(redTotal / imageArea, greenTotal / imageArea, blueTotal / imageArea);
        }
    } else {
        if (image.format() != QImage::Format_ARGB32) {
            image = image.convertToFormat(QImage::Format_ARGB32);
        }
        
        // check for translucency/false transparency
        // int opaquePixels = 0;
        // int translucentPixels = 0;
        // int redTotal = 0, greenTotal = 0, blueTotal = 0, alphaTotal = 0;
        for (int y = 0; y < image.height(); y++) {
            for (int x = 0; x < image.width(); x++) {
                QRgb rgb = image.pixel(x, y);
                redTotal += qRed(rgb);
                greenTotal += qGreen(rgb);
                blueTotal += qBlue(rgb);
                int alpha = qAlpha(rgb);
                alphaTotal += alpha;
                if (alpha == EIGHT_BIT_MAXIMUM) {
                    opaquePixels++;
                } else if (alpha != 0) {
                    translucentPixels++;
                }
            }
        }
        if (opaquePixels == imageArea) {
            qCDebug(modelLog) << "Image with alpha channel is completely opaque:" << QString(srcImageName.c_str());
            image = image.convertToFormat(QImage::Format_RGB888);
        }
        
        averageColor = QColor(redTotal / imageArea,
                              greenTotal / imageArea, blueTotal / imageArea, alphaTotal / imageArea);
        
        //isTransparent = (translucentPixels >= imageArea / 2);
    }
    
    gpu::Texture* theTexture = nullptr;
    if ((image.width() > 0) && (image.height() > 0)) {
        
        // bool isLinearRGB = true; //(_type == NORMAL_TEXTURE) || (_type == EMISSIVE_TEXTURE);
        bool isLinearRGB = false; //(_type == NORMAL_TEXTURE) || (_type == EMISSIVE_TEXTURE);
        
        gpu::Element formatGPU = gpu::Element(gpu::VEC3, gpu::UINT8, (isLinearRGB ? gpu::RGB : gpu::SRGB));
        gpu::Element formatMip = gpu::Element(gpu::VEC3, gpu::UINT8, (isLinearRGB ? gpu::RGB : gpu::SRGB));
        if (image.hasAlphaChannel()) {
            formatGPU = gpu::Element(gpu::VEC4, gpu::UINT8, (isLinearRGB ? gpu::RGBA : gpu::SRGBA));
            formatMip = gpu::Element(gpu::VEC4, gpu::UINT8, (isLinearRGB ? gpu::BGRA : gpu::SBGRA));
        }
        

            const CubeLayout CUBEMAP_LAYOUTS[] = {
                // Here is the expected layout for the faces in an image with the 1/6 aspect ratio:
                //
                //         WIDTH
                //       <------>
                //    ^  +------+
                //    |  |      |
                //    |  |  +X  |
                //    |  |      |
                //    H  +------+
                //    E  |      |
                //    I  |  -X  |
                //    G  |      |
                //    H  +------+
                //    T  |      |
                //    |  |  +Y  |
                //    |  |      |
                //    |  +------+
                //    |  |      |
                //    |  |  -Y  |
                //    |  |      |
                //    H  +------+
                //    E  |      |
                //    I  |  +Z  |
                //    G  |      |
                //    H  +------+
                //    T  |      |
                //    |  |  -Z  |
                //    |  |      |
                //    V  +------+
                //
                //    FaceWidth = width = height / 6
                {   1, 6,
                    {0, 0, true, false},
                    {0, 1, true, false},
                    {0, 2, false, true},
                    {0, 3, false, true},
                    {0, 4, true, false},
                    {0, 5, true, false}
                },
                
                // Here is the expected layout for the faces in an image with the 3/4 aspect ratio:
                //
                //       <-----------WIDTH----------->
                //    ^  +------+------+------+------+
                //    |  |      |      |      |      |
                //    |  |      |  +Y  |      |      |
                //    |  |      |      |      |      |
                //    H  +------+------+------+------+
                //    E  |      |      |      |      |
                //    I  |  -X  |  -Z  |  +X  |  +Z  |
                //    G  |      |      |      |      |
                //    H  +------+------+------+------+
                //    T  |      |      |      |      |
                //    |  |      |  -Y  |      |      |
                //    |  |      |      |      |      |
                //    V  +------+------+------+------+
                //
                //    FaceWidth = width / 4 = height / 3
                {   4, 3,
                    {2, 1, true, false},
                    {0, 1, true, false},
                    {1, 0, false, true},
                    {1, 2, false, true},
                    {3, 1, true, false},
                    {1, 1, true, false}
                },
                
                // Here is the expected layout for the faces in an image with the 4/3 aspect ratio:
                //
                //       <-------WIDTH-------->
                //    ^  +------+------+------+
                //    |  |      |      |      |
                //    |  |      |  +Y  |      |
                //    |  |      |      |      |
                //    H  +------+------+------+
                //    E  |      |      |      |
                //    I  |  -X  |  -Z  |  +X  |
                //    G  |      |      |      |
                //    H  +------+------+------+
                //    T  |      |      |      |
                //    |  |      |  -Y  |      |
                //    |  |      |      |      |
                //    |  +------+------+------+
                //    |  |      |      |      |
                //    |  |      |  +Z! |      | <+Z is upside down!
                //    |  |      |      |      |
                //    V  +------+------+------+
                //
                //    FaceWidth = width / 3 = height / 4
                {   3, 4,
                    {2, 1, true, false},
                    {0, 1, true, false},
                    {1, 0, false, true},
                    {1, 2, false, true},
                    {1, 3, false, true},
                    {1, 1, true, false}
                }
            };
            const int NUM_CUBEMAP_LAYOUTS = sizeof(CUBEMAP_LAYOUTS) / sizeof(CubeLayout);
            
            // Find the layout of the cubemap in the 2D image
            int foundLayout = -1;
            for (int i = 0; i < NUM_CUBEMAP_LAYOUTS; i++) {
                if ((image.height() * CUBEMAP_LAYOUTS[i]._widthRatio) == (image.width() * CUBEMAP_LAYOUTS[i]._heightRatio)) {
                    foundLayout = i;
                    break;
                }
            }
            
            std::vector<QImage> faces;
            // If found, go extract the faces as separate images
            if (foundLayout >= 0) {
                auto& layout = CUBEMAP_LAYOUTS[foundLayout];
                int faceWidth = image.width() / layout._widthRatio;
                
                faces.push_back(image.copy(QRect(layout._faceXPos._x * faceWidth, layout._faceXPos._y * faceWidth, faceWidth, faceWidth)).mirrored(layout._faceXPos._horizontalMirror, layout._faceXPos._verticalMirror));
                faces.push_back(image.copy(QRect(layout._faceXNeg._x * faceWidth, layout._faceXNeg._y * faceWidth, faceWidth, faceWidth)).mirrored(layout._faceXNeg._horizontalMirror, layout._faceXNeg._verticalMirror));
                faces.push_back(image.copy(QRect(layout._faceYPos._x * faceWidth, layout._faceYPos._y * faceWidth, faceWidth, faceWidth)).mirrored(layout._faceYPos._horizontalMirror, layout._faceYPos._verticalMirror));
                faces.push_back(image.copy(QRect(layout._faceYNeg._x * faceWidth, layout._faceYNeg._y * faceWidth, faceWidth, faceWidth)).mirrored(layout._faceYNeg._horizontalMirror, layout._faceYNeg._verticalMirror));
                faces.push_back(image.copy(QRect(layout._faceZPos._x * faceWidth, layout._faceZPos._y * faceWidth, faceWidth, faceWidth)).mirrored(layout._faceZPos._horizontalMirror, layout._faceZPos._verticalMirror));
                faces.push_back(image.copy(QRect(layout._faceZNeg._x * faceWidth, layout._faceZNeg._y * faceWidth, faceWidth, faceWidth)).mirrored(layout._faceZNeg._horizontalMirror, layout._faceZNeg._verticalMirror));
            } else {
                qCDebug(modelLog) << "Failed to find a known cube map layout from this image:" << QString(srcImageName.c_str());
                return nullptr;
            }
            
            // If the 6 faces have been created go on and define the true Texture
            if (faces.size() == gpu::Texture::NUM_FACES_PER_TYPE[gpu::Texture::TEX_CUBE]) {
                theTexture = gpu::Texture::createCube(formatGPU, faces[0].width(), gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_MIP_LINEAR, gpu::Sampler::WRAP_CLAMP));
                theTexture->autoGenerateMips(-1);
                int f = 0;
                for (auto& face : faces) {
                    theTexture->assignStoredMipFace(0, formatMip, face.byteCount(), face.constBits(), f);
                    f++;
                }
                
                // GEnerate irradiance while we are at it
                theTexture->generateIrradiance();
            }
    }
    
    return theTexture;
}
示例#28
0
gpu::Texture* TextureUsage::processCubeTextureColorFromImage(const QImage& srcImage, const std::string& srcImageName, bool isLinear, bool doCompress, bool generateMips, bool generateIrradiance) {
    gpu::Texture* theTexture = nullptr;
    if ((srcImage.width() > 0) && (srcImage.height() > 0)) {
        QImage image = srcImage;
        if (image.format() != QImage::Format_RGB888) {
            image = image.convertToFormat(QImage::Format_RGB888);
        }

        gpu::Element formatGPU;
        gpu::Element formatMip;
        defineColorTexelFormats(formatGPU, formatMip, image, isLinear, doCompress);

        // Find the layout of the cubemap in the 2D image
        int foundLayout = CubeLayout::findLayout(image.width(), image.height());

        std::vector<QImage> faces;
        // If found, go extract the faces as separate images
        if (foundLayout >= 0) {
            auto& layout = CubeLayout::CUBEMAP_LAYOUTS[foundLayout];
            if (layout._type == CubeLayout::FLAT) {
                int faceWidth = image.width() / layout._widthRatio;

                faces.push_back(image.copy(QRect(layout._faceXPos._x * faceWidth, layout._faceXPos._y * faceWidth, faceWidth, faceWidth)).mirrored(layout._faceXPos._horizontalMirror, layout._faceXPos._verticalMirror));
                faces.push_back(image.copy(QRect(layout._faceXNeg._x * faceWidth, layout._faceXNeg._y * faceWidth, faceWidth, faceWidth)).mirrored(layout._faceXNeg._horizontalMirror, layout._faceXNeg._verticalMirror));
                faces.push_back(image.copy(QRect(layout._faceYPos._x * faceWidth, layout._faceYPos._y * faceWidth, faceWidth, faceWidth)).mirrored(layout._faceYPos._horizontalMirror, layout._faceYPos._verticalMirror));
                faces.push_back(image.copy(QRect(layout._faceYNeg._x * faceWidth, layout._faceYNeg._y * faceWidth, faceWidth, faceWidth)).mirrored(layout._faceYNeg._horizontalMirror, layout._faceYNeg._verticalMirror));
                faces.push_back(image.copy(QRect(layout._faceZPos._x * faceWidth, layout._faceZPos._y * faceWidth, faceWidth, faceWidth)).mirrored(layout._faceZPos._horizontalMirror, layout._faceZPos._verticalMirror));
                faces.push_back(image.copy(QRect(layout._faceZNeg._x * faceWidth, layout._faceZNeg._y * faceWidth, faceWidth, faceWidth)).mirrored(layout._faceZNeg._horizontalMirror, layout._faceZNeg._verticalMirror));
            } else if (layout._type == CubeLayout::EQUIRECTANGULAR) {
                // THe face width is estimated from the input image
                const int EQUIRECT_FACE_RATIO_TO_WIDTH = 4;
                const int EQUIRECT_MAX_FACE_WIDTH = 2048;
                int faceWidth = std::min(image.width() / EQUIRECT_FACE_RATIO_TO_WIDTH, EQUIRECT_MAX_FACE_WIDTH);
                for (int face = gpu::Texture::CUBE_FACE_RIGHT_POS_X; face < gpu::Texture::NUM_CUBE_FACES; face++) {
                    QImage faceImage = CubeLayout::extractEquirectangularFace(image, (gpu::Texture::CubeFace) face, faceWidth);
                    faces.push_back(faceImage);
                }
            }
        } else {
            qCDebug(modelLog) << "Failed to find a known cube map layout from this image:" << QString(srcImageName.c_str());
            return nullptr;
        }

        // If the 6 faces have been created go on and define the true Texture
        if (faces.size() == gpu::Texture::NUM_FACES_PER_TYPE[gpu::Texture::TEX_CUBE]) {
            theTexture = gpu::Texture::createCube(formatGPU, faces[0].width(), gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_MIP_LINEAR, gpu::Sampler::WRAP_CLAMP));
            int f = 0;
            for (auto& face : faces) {
                theTexture->assignStoredMipFace(0, formatMip, face.byteCount(), face.constBits(), f);
                if (generateMips) {
                    generateFaceMips(theTexture, face, formatMip, f);
                }
                f++;
            }

            if (generateMips) {
                theTexture->autoGenerateMips(-1);
            }

            // Generate irradiance while we are at it
            if (generateIrradiance) {
                theTexture->generateIrradiance();
            }
        }
    }

    return theTexture;
}
void AsyncImageCreator::run() {
  // first we make sure we have an image
  QString cacheFileName;
  bool hasPreview = false;

  if (d->mImage.isNull() && d->mInputFileName.isEmpty() &&
      (!d->mDataArray.isEmpty() || !d->mDataArray.isNull())) {
    d->mImage.loadFromData(d->mDataArray);
    cacheFileName = QCryptographicHash::hash(d->mDataArray,
                                             QCryptographicHash::Md5).toHex();
  } else if (d->mImage.isNull() && !d->mInputFileName.isEmpty()) {
    cacheFileName =
        QCryptographicHash::hash(QByteArray().append(d->mInputFileName),
                                 QCryptographicHash::Md5).toHex();
    d->mFileName = d->mInputFileName;
    // cache preview
    QString cachePreviewFilePath = QDir::toNativeSeparators(
        d->mStorePrefix + "/" + cacheFileName + "_preview.png");
    QFile cachePreviewFile(cachePreviewFilePath);
    if (cachePreviewFile.exists()) {
      d->mThumbNail = QImage(cachePreviewFilePath);
    } else {
      d->mImage = QImage(d->mInputFileName);
      d->mThumbNail =
          d->mImage.scaled(d->mThumbNailSize, Qt::KeepAspectRatioByExpanding);
      d->saveFile(cachePreviewFilePath, d->mThumbNail);
    }

    hasPreview = true;
  } else {
    d->mDataArray = imageToByteArray(d->mImage);
    cacheFileName = QCryptographicHash::hash(d->mDataArray,
                                             QCryptographicHash::Md5).toHex();
  }

  QString cacheFilePath =
      QDir::toNativeSeparators(d->mStorePrefix + "/" + cacheFileName + ".png");

  if (d->mOffline && !d->mStorePrefix.isEmpty()) {
    d->saveFile(cacheFilePath, d->mImage);
    d->mFileName = cacheFilePath;
  }

  // create the thumbnail
  if (!hasPreview)
    d->mThumbNail =
        d->mImage.scaled(d->mThumbNailSize, Qt::KeepAspectRatioByExpanding);

  // scale operations
  if (d->mScaleHeight > 0) {
    d->mHeightScaledImage = d->mImage.scaledToHeight(d->mScaleHeight);
  }

  if (d->mScaleWidth > 0) {
    d->mWidthScaledImage = d->mImage.scaledToWidth(d->mScaleWidth);
  }

  if (d->mCropImage) {
    QImage imageToCrop = d->mImage.scaledToHeight(d->mCropRect.height());
    d->mCropedImage = imageToCrop.copy(d->mCropRect);
  }

  Q_EMIT ready();
}
示例#30
0
文件: htmlview.cpp 项目: delight/Pana
QString
HTMLView::loadStyleSheet()
{
    QString themeName = PanaConfig::contextBrowserStyleSheet().latin1();
    const QString file = kapp->dirs()->findResource( "data","pana/themes/" + themeName + "/stylesheet.css" );

    QString styleSheet;
    if ( themeName != "Default" && QFile::exists( file ) )
    {
        const QString CSSLocation = kapp->dirs()->findResource( "data","pana/themes/" + themeName + "/stylesheet.css" );
        QFile ExternalCSS( CSSLocation );
        if ( !ExternalCSS.open( IO_ReadOnly ) )
            return QString(); //FIXME: should actually return the default style sheet, then

        const QString pxSize = QString::number( ContextBrowser::instance()->fontMetrics().height() - 4 );
        const QString fontFamily = PanaConfig::useCustomFonts() ?
                                        PanaConfig::contextBrowserFont().family() :
                                        QApplication::font().family();
        const QString text   = ContextBrowser::instance()->colorGroup().text().name();
        const QString link   = ContextBrowser::instance()->colorGroup().link().name();
        const QString fg     = ContextBrowser::instance()->colorGroup().highlightedText().name();
        const QString bg     = ContextBrowser::instance()->colorGroup().highlight().name();
        const QString base   = ContextBrowser::instance()->colorGroup().base().name();
        const QColor bgColor = ContextBrowser::instance()->colorGroup().highlight();
        QColor gradientColor = bgColor;

        //we have to set the color for body due to a KHTML bug
        //KHTML sets the base color but not the text color
        styleSheet = QString( "body { margin: 8px; font-size: %1px; color: %2; background-color: %3; font-family: %4; }" )
                .arg( pxSize )
                .arg( text )
                .arg( PanaConfig::schemePana() ? fg : gradientColor.name() )
                .arg( fontFamily );

        QTextStream eCSSts( &ExternalCSS );
        QString tmpCSS = eCSSts.read();
        ExternalCSS.close();

        tmpCSS.replace( "./", KURL::fromPathOrURL( CSSLocation ).directory( false ) );
        tmpCSS.replace( "PANA_FONTSIZE-2", pxSize );
        tmpCSS.replace( "PANA_FONTSIZE", pxSize );
        tmpCSS.replace( "PANA_FONTSIZE+2", pxSize );
        tmpCSS.replace( "PANA_FONTFAMILY", fontFamily );
        tmpCSS.replace( "PANA_TEXTCOLOR", text );
        tmpCSS.replace( "PANA_LINKCOLOR", link );
        tmpCSS.replace( "PANA_BGCOLOR", bg );
        tmpCSS.replace( "PANA_FGCOLOR", fg );
        tmpCSS.replace( "PANA_BASECOLOR", base );
        tmpCSS.replace( "PANA_DARKBASECOLOR", ContextBrowser::instance()->colorGroup().base().dark( 120 ).name() );
        tmpCSS.replace( "PANA_GRADIENTCOLOR", gradientColor.name() );

        styleSheet += tmpCSS;
    }
    else
    {
        int pxSize = ContextBrowser::instance()->fontMetrics().height() - 4;
        const QString fontFamily = PanaConfig::useCustomFonts() ? PanaConfig::contextBrowserFont().family() : QApplication::font().family();
        const QString text = ContextBrowser::instance()->colorGroup().text().name();
        const QString link = ContextBrowser::instance()->colorGroup().link().name();
        const QString fg   = ContextBrowser::instance()->colorGroup().highlightedText().name();
        const QString bg   = ContextBrowser::instance()->colorGroup().highlight().name();
        const QColor baseColor = ContextBrowser::instance()->colorGroup().base();
        const QColor bgColor = ContextBrowser::instance()->colorGroup().highlight();
        const QColor gradientColor = bgColor;

        if ( !m_bgGradientImage ) {
            m_bgGradientImage = new KTempFile( locateLocal( "tmp", "gradient" ), ".png", 0600 );
            QImage image = KImageEffect::gradient( QSize( 600, 1 ), gradientColor, gradientColor.light( 130 ), KImageEffect::PipeCrossGradient );
            image.save( m_bgGradientImage->file(), "PNG" );
            m_bgGradientImage->close();
        }

        if ( !m_headerGradientImage ) {
            m_headerGradientImage = new KTempFile( locateLocal( "tmp", "gradient_header" ), ".png", 0600 );
            QImage imageH = KImageEffect::unbalancedGradient( QSize( 1, 10 ), bgColor, gradientColor.light( 130 ), KImageEffect::VerticalGradient, 100, -100 );
            imageH.copy( 0, 1, 1, 9 ).save( m_headerGradientImage->file(), "PNG" );
            m_headerGradientImage->close();
        }

        if ( !m_shadowGradientImage ) {
            m_shadowGradientImage = new KTempFile( locateLocal( "tmp", "gradient_shadow" ), ".png", 0600 );
            QImage imageS = KImageEffect::unbalancedGradient( QSize( 1, 10 ), baseColor, Qt::gray, KImageEffect::VerticalGradient, 100, -100 );
            imageS.save( m_shadowGradientImage->file(), "PNG" );
            m_shadowGradientImage->close();
        }

        //unlink the files for us on deletion
        m_bgGradientImage->setAutoDelete( true );
        m_headerGradientImage->setAutoDelete( true );
        m_shadowGradientImage->setAutoDelete( true );

        //we have to set the color for body due to a KHTML bug
        //KHTML sets the base color but not the text color
        styleSheet = QString( "body { margin: 4px; font-size: %1px; color: %2; background-color: %3; background-image: url( %4 ); background-repeat: repeat; font-family: %5; }" )
                .arg( pxSize )
                .arg( text )
                .arg( PanaConfig::schemePana() ? fg : gradientColor.name() )
                .arg( m_bgGradientImage->name() )
                .arg( fontFamily );

        //text attributes
        styleSheet += QString( "h1 { font-size: %1px; }" ).arg( pxSize + 8 );
        styleSheet += QString( "h2 { font-size: %1px; }" ).arg( pxSize + 6 );
        styleSheet += QString( "h3 { font-size: %1px; }" ).arg( pxSize + 4 );
        styleSheet += QString( "h4 { font-size: %1px; }" ).arg( pxSize + 3 );
        styleSheet += QString( "h5 { font-size: %1px; }" ).arg( pxSize + 2 );
        styleSheet += QString( "h6 { font-size: %1px; }" ).arg( pxSize + 1 );
        styleSheet += QString( "a { font-size: %1px; color: %2; }" ).arg( pxSize ).arg( text );
        styleSheet += QString( ".info { display: block; margin-left: 4px; font-weight: normal; }" );

        styleSheet += QString( ".song a { display: block; padding: 1px 2px; font-weight: normal; text-decoration: none; }" );
        styleSheet += QString( ".song a:hover { color: %1; background-color: %2; }" ).arg( fg ).arg( bg );
        styleSheet += QString( ".song-title { font-weight: bold; }" );
        styleSheet += QString( ".song-place { font-size: %1px; font-weight: bold; }" ).arg( pxSize + 3 );

        //box: the base container for every block (border hilighted on hover, 'A' without underlining)
        styleSheet += QString( ".box { border: solid %1 1px; text-align: left; margin-bottom: 10px; }" ).arg( bg );
        styleSheet += QString( ".box a { text-decoration: none; }" );
        styleSheet += QString( ".box:hover { border: solid %1 1px; }" ).arg( text );

        //box contents: header, body, rows and alternate-rows
        styleSheet += QString( ".box-header { color: %1; background-color: %2; background-image: url( %4 ); background-repeat: repeat-x; font-size: %3px; font-weight: bold; padding: 1px 0.5em; border-bottom: 1px solid #000; }" )
                .arg( fg )
                .arg( bg )
                .arg( pxSize + 2 )
                .arg( m_headerGradientImage->name() );

        styleSheet += QString( ".box-body { padding: 2px; background-color: %1; background-image: url( %2 ); background-repeat: repeat-x; font-size:%3px; }" )
                .arg( ContextBrowser::instance()->colorGroup().base().name() )
                .arg( m_shadowGradientImage->name() )
                .arg( pxSize );

        //"Related Artists" related styles
        styleSheet += QString( ".box-header-nav { color: %1; background-color: %2; font-size: %3px; font-weight: bold; padding: 1px 0.5em; border-bottom: 1px solid #000; text-align: right; }" )
                .arg( fg )
                .arg( bg )
                .arg( pxSize );

        //"Albums by ..." related styles
        styleSheet += QString( ".album-header:hover { color: %1; background-color: %2; cursor: pointer; }" ).arg( fg ).arg( bg );
        styleSheet += QString( ".album-header:hover a { color: %1; }" ).arg( fg );
        styleSheet += QString( ".album-body { background-color: %1; border-bottom: solid %2 1px; border-top: solid %3 1px; }" ).arg( ContextBrowser::instance()->colorGroup().base().name() ).arg( bg ).arg( bg );
        styleSheet += QString( ".album-title { font-weight: bold; }" );
        styleSheet += QString( ".album-info { float:right; padding-right:4px; font-size: %1px }" ).arg( pxSize );
        styleSheet += QString( ".album-length { float:right; padding-right:4px; font-size: %1px; clear:right; }" ).arg( pxSize );
        styleSheet += QString( ".album-image { padding-right: 4px; }" );
        styleSheet += QString( ".album-song a { display: block; padding: 1px 2px; font-weight: normal; text-decoration: none; }" );
        styleSheet += QString( ".album-song a:hover { color: %1; background-color: %2; }" ).arg( fg ).arg( bg );
        styleSheet += QString( ".album-song-trackno { font-weight: bold; }" );

        styleSheet += QString( ".disc-separator { color: %1; border-bottom: 1px solid %2; }" ).arg( bg ).arg( bg );
        styleSheet += QString( ".disc-separator a { display: block; padding: 1px 2px; font-weight: normal; text-decoration: none; }" );
        styleSheet += QString( ".disc-separator a:hover { color: %1; background-color: %2; }" ).arg( fg ).arg( bg );

        styleSheet += QString( ".button { width: 100%; }" );

        //boxes used to display score (sb: score box)
        styleSheet += QString( ".sbtext { text-align: right; padding: 0px 4px; }" );
        styleSheet += QString( ".sbinner { height: 8px; background-color: %1; border: solid %2 1px; }" )
                            .arg( ContextBrowser::instance()->colorGroup().highlight().name() )
                            .arg( ContextBrowser::instance()->colorGroup().highlightedText().name() );
        styleSheet += QString( ".sbouter { width: 52px; height: 10px; background-color: %1; border: solid %2 1px; }" )
                            .arg( ContextBrowser::instance()->colorGroup().base().dark( 120 ).name() )
                            .arg( ContextBrowser::instance()->colorGroup().highlight().name() );

        styleSheet += QString( ".ratingBox { padding: 0px 4px; }" );
        styleSheet += QString( ".ratingStar { height: 0.9em; }" );

        styleSheet += QString( ".statsBox { border-left: solid %1 1px; }" )
                      .arg( ContextBrowser::instance()->colorGroup().base().dark( 120 ).name() );

        styleSheet += QString( "#current_box-header-album { font-weight: normal; }" );
        styleSheet += QString( "#current_box-information-td { text-align: right; vertical-align: bottom; padding: 3px; }" );
        styleSheet += QString( "#current_box-largecover-td { text-align: left; width: 100px; padding: 0; vertical-align: bottom; }" );
        styleSheet += QString( "#current_box-largecover-image { padding: 4px; vertical-align: bottom; }" );

        styleSheet += QString( "#wiki_box-body a { color: %1; }" ).arg( link );
        styleSheet += QString( "#wiki_box-body a:hover { text-decoration: underline; }" );

        //labels in tag dialog
        styleSheet += ".label a:hover { font-weight: bold; }";
        styleSheet += QString( ".label.size1 { font-size: %1px; }" ).arg( pxSize );
        styleSheet += QString( ".label.size2 { font-size: %1px; }" ).arg( pxSize + 1 );
        styleSheet += QString( ".label.size3 { font-size: %1px; }" ).arg( pxSize + 2 );
        styleSheet += QString( ".label.size4 { font-size: %1px; }" ).arg( pxSize + 3 );
        styleSheet += QString( ".label.size5 { font-size: %1px; }" ).arg( pxSize + 4);
        styleSheet += QString( ".label.size6 { font-size: %1px; }" ).arg( pxSize + 5 );
        styleSheet += QString( ".label.size7 { font-size: %1px; }" ).arg( pxSize + 6 );
        styleSheet += QString( ".label.size8 { font-size: %1px; }" ).arg( pxSize + 7 );
        styleSheet += QString( ".label.size9 { font-size: %1px; }" ).arg( pxSize + 8 );
        styleSheet += QString( ".label.size10 { font-size: %1px; }" ).arg( pxSize + 9 );
    }

    return styleSheet;
}