示例#1
0
	bool readImage(SImage& image, MemChunk& data, int index)
	{
		// Get info
		SImage::info_t info = getInfo(data, index);

		// Create image from data
		image.create(info.width, info.height, PALMASK);
		data.read(imageData(image), info.width*info.height, 0);
		image.fillAlpha(255);

		return true;
	}
示例#2
0
KoClipPath *PictureShape::generateClipPath()
{
    QPainterPath path = _Private::generateOutline(imageData()->image());
    path = path * QTransform().scale(size().width(), size().height());

    KoPathShape *pathShape = KoPathShape::createShapeFromPainterPath(path);

    //createShapeFromPainterPath converts the path topleft into a shape topleft
    //and the pathShape needs to be on top of us. So to preserve both we do:
    pathShape->setTransformation(pathShape->transformation() * transformation());

    return new KoClipPath(this, new KoClipData(pathShape));
}
示例#3
0
static void dumpBitmap(CGContextRef bitmapContext, const char* checksum)
{
    RetainPtr<CGImageRef> image(AdoptCF, CGBitmapContextCreateImage(bitmapContext));
    RetainPtr<CFMutableDataRef> imageData(AdoptCF, CFDataCreateMutable(0, 0));
    RetainPtr<CGImageDestinationRef> imageDest(AdoptCF, CGImageDestinationCreateWithData(imageData.get(), kUTTypePNG, 1, 0));
    CGImageDestinationAddImage(imageDest.get(), image.get(), 0);
    CGImageDestinationFinalize(imageDest.get());

    const unsigned char* data = CFDataGetBytePtr(imageData.get());
    const size_t dataLength = CFDataGetLength(imageData.get());

    printPNG(data, dataLength, checksum);
}
示例#4
0
void FEComposite::apply(Filter* filter)
{
    m_in->apply(filter);
    m_in2->apply(filter);
    if (!m_in->resultImage() || !m_in2->resultImage())
        return;

    GraphicsContext* filterContext = getEffectContext();
    if (!filterContext)
        return;

    FloatRect srcRect = FloatRect(0.f, 0.f, -1.f, -1.f);
    switch (m_type) {
    case FECOMPOSITE_OPERATOR_OVER:
        filterContext->drawImageBuffer(m_in2->resultImage(), DeviceColorSpace, calculateDrawingRect(m_in2->scaledSubRegion()));
        filterContext->drawImageBuffer(m_in->resultImage(), DeviceColorSpace, calculateDrawingRect(m_in->scaledSubRegion()));
        break;
    case FECOMPOSITE_OPERATOR_IN:
        filterContext->save();
        filterContext->clipToImageBuffer(m_in2->resultImage(), calculateDrawingRect(m_in2->scaledSubRegion()));
        filterContext->drawImageBuffer(m_in->resultImage(), DeviceColorSpace, calculateDrawingRect(m_in->scaledSubRegion()));
        filterContext->restore();
        break;
    case FECOMPOSITE_OPERATOR_OUT:
        filterContext->drawImageBuffer(m_in->resultImage(), DeviceColorSpace, calculateDrawingRect(m_in->scaledSubRegion()));
        filterContext->drawImageBuffer(m_in2->resultImage(), DeviceColorSpace, calculateDrawingRect(m_in2->scaledSubRegion()), srcRect, CompositeDestinationOut);
        break;
    case FECOMPOSITE_OPERATOR_ATOP:
        filterContext->drawImageBuffer(m_in2->resultImage(), DeviceColorSpace, calculateDrawingRect(m_in2->scaledSubRegion()));
        filterContext->drawImageBuffer(m_in->resultImage(), DeviceColorSpace, calculateDrawingRect(m_in->scaledSubRegion()), srcRect, CompositeSourceAtop);
        break;
    case FECOMPOSITE_OPERATOR_XOR:
        filterContext->drawImageBuffer(m_in2->resultImage(), DeviceColorSpace, calculateDrawingRect(m_in2->scaledSubRegion()));
        filterContext->drawImageBuffer(m_in->resultImage(), DeviceColorSpace, calculateDrawingRect(m_in->scaledSubRegion()), srcRect, CompositeXOR);
        break;
    case FECOMPOSITE_OPERATOR_ARITHMETIC: {
        IntRect effectADrawingRect = calculateDrawingIntRect(m_in->scaledSubRegion());
        RefPtr<CanvasPixelArray> srcPixelArrayA(m_in->resultImage()->getPremultipliedImageData(effectADrawingRect)->data());

        IntRect effectBDrawingRect = calculateDrawingIntRect(m_in2->scaledSubRegion());
        RefPtr<ImageData> imageData(m_in2->resultImage()->getPremultipliedImageData(effectBDrawingRect));
        CanvasPixelArray* srcPixelArrayB(imageData->data());

        arithmetic(srcPixelArrayA, srcPixelArrayB, m_k1, m_k2, m_k3, m_k4);
        resultImage()->putPremultipliedImageData(imageData.get(), IntRect(IntPoint(), resultImage()->size()), IntPoint());
        }
        break;
    default:
        break;
    }
}
示例#5
0
	bool writeImage(SImage& image, MemChunk& data, Palette* pal, int index)
	{
		// Can't write if RGBA
		if (image.getType() == RGBA)
			return false;

		// Check size
		if (!validSize(image.getWidth(), image.getHeight()))
			return false;

		// Just dump image data to memchunk
		data.clear();
		data.write(imageData(image), image.getWidth() * image.getHeight());

		return true;
	}
示例#6
0
bool ImageDataObject::checkIfStructureChanged()
{
    const auto superclassResult = CoordinateTransformableDataObject::checkIfStructureChanged();

    decltype(m_extent) newExtent;
    imageData().GetExtent(newExtent.data());

    bool changed = newExtent != m_extent;

    if (changed)
    {
        m_extent = newExtent;
    }

    return superclassResult || changed;
}
示例#7
0
bb::ImageData PictureHelper::fromQImage(const QImage &qImage)
{
	bb::ImageData imageData(bb::PixelFormat::RGBA_Premultiplied, qImage.width(), qImage.height());

	unsigned char *dstLine = imageData.pixels();
	for (int y = 0; y < imageData.height(); y++) {
		unsigned char * dst = dstLine;
		for (int x = 0; x < imageData.width(); x++) {
			QRgb srcPixel = qImage.pixel(x, y);
			*dst++ = qRed(srcPixel);
			*dst++ = qGreen(srcPixel);
			*dst++ = qBlue(srcPixel);
			*dst++ = qAlpha(srcPixel);
		}
		dstLine += imageData.bytesPerLine();
	}

	return imageData;
}
示例#8
0
void ScreenManager::postImage()
{
    emit signal_printToLog("Buffer reading");

    buffer.open(QIODevice::ReadOnly);
    QByteArray base64image(buffer.readAll().toBase64());
    buffer.close();

    emit signal_printToLog(QString("Buffer read: %1").arg(base64image.size()));

    emit signal_printToLog("Forming request");

    QByteArray imageData("image=");
    imageData.append(base64image);
    imageData.replace("/", "%2F");
    imageData.replace("+", "%2B");

    headers.append("POST /upload HTTP/1.1\r\n");
    headers.append("Content-Type: application/x-www-form-urlencoded\r\n");
    headers.append("Content-Length: ");
    headers.append(QString::number(imageData.size()).toAscii());
    headers.append("\r\n");
    headers.append("Connection: close\r\n");
    headers.append("Accept-Encoding: identity\r\n");
    headers.append("Host: cropme.ru\r\n\r\n");

    emit signal_printToLog("Request formed, sending");

    if(socket.isWritable())
    {
        socket.write(headers);
        socket.write(imageData);
        socket.flush();

        emit signal_printToLog("All sent");
    }
    else
    {
        QMessageBox::warning(0, tr("Error"), tr("unwritable socket"));
    }
}
示例#9
0
String ImageBuffer::toDataURL(const String& mimeType) const
{
    ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));

    RetainPtr<CGImageRef> image(AdoptCF, CGBitmapContextCreateImage(context()->platformContext()));
    if (!image)
        return "data:,";

    size_t width = CGImageGetWidth(image.get());
    size_t height = CGImageGetHeight(image.get());

    OwnArrayPtr<uint32_t> imageData(new uint32_t[width * height]);
    if (!imageData)
        return "data:,";
    
    RetainPtr<CGImageRef> transformedImage(AdoptCF, CGBitmapContextCreateImage(context()->platformContext()));
    if (!transformedImage)
        return "data:,";

    RetainPtr<CFMutableDataRef> transformedImageData(AdoptCF, CFDataCreateMutable(kCFAllocatorDefault, 0));
    if (!transformedImageData)
        return "data:,";

    RetainPtr<CGImageDestinationRef> imageDestination(AdoptCF, CGImageDestinationCreateWithData(transformedImageData.get(),
        utiFromMIMEType(mimeType).get(), 1, 0));
    if (!imageDestination)
        return "data:,";

    CGImageDestinationAddImage(imageDestination.get(), transformedImage.get(), 0);
    CGImageDestinationFinalize(imageDestination.get());

    Vector<char> in;
    in.append(CFDataGetBytePtr(transformedImageData.get()), CFDataGetLength(transformedImageData.get()));

    Vector<char> out;
    base64Encode(in, out);
    out.append('\0');

    return String::format("data:%s;base64,%s", mimeType.utf8().data(), out.data());
}
示例#10
0
void CoverWidget::dropEvent(QDropEvent *e) {
	auto mimeData = e->mimeData();

	QImage img;
	if (mimeData->hasImage()) {
		img = qvariant_cast<QImage>(mimeData->imageData());
	} else {
		const auto &urls = mimeData->urls();
		if (urls.size() == 1) {
			auto &url = urls.at(0);
			if (url.isLocalFile()) {
				img = App::readImage(psConvertFileUrl(url));
			}
		}
	}

	if (!_dropArea->hiding()) {
		_dropArea->hideAnimated(func(this, &CoverWidget::dropAreaHidden));
	}
	e->acceptProposedAction();

	showSetPhotoBox(img);
}
示例#11
0
std::vector<float> Image::getRawPixelData()
{
	if (samplingScheme.stepSize.width == 1 && samplingScheme.stepSize.height == 1)
	{
		return getRawPixelDataSimulated();
	}
	else // easy non AVX implementation
	{
		std::vector<float> imageData(imageSize.width*imageSize.height * 4);
		size_t offset = 0;
		PixelData32 pixel;
		for (uint y = 0; y < imageSize.height; y++)
		{
			for (uint x = 0; x < imageSize.width; x++)
			{
				getPixel(pixel, x, y);
				memcpy(imageData.data() + offset, &pixel, sizeof(PixelData32));
				offset += sizeof(PixelData32) / sizeof(float);
			}
		}
		return imageData;
	}
}
示例#12
0
std::vector<float> Image::getRawPixelDataSimulated()
{
	std::vector<float> imageData(simulatedSize.width*simulatedSize.height * 4);

	if (simulatedSize == channelSizes[0] && simulatedSize == channelSizes[1] && simulatedSize == channelSizes[2]) {
		transposeFloatAVX_reverse(channels->red(), channels->green(), channels->blue(), &imageData[0], simulatedSize.width*simulatedSize.height);
	} 
	else // easy non AVX implementation
	{
		size_t offset = 0;
		PixelData32 pixel;
		for (uint y = 0; y < simulatedSize.height; y++)
		{
			for (uint x = 0; x < simulatedSize.width; x++)
			{
				getPixel(pixel, x, y);
				memcpy(imageData.data() + offset, &pixel, sizeof(PixelData32));
				offset += sizeof(PixelData32) / sizeof(float);
			}
		}
	}

	return imageData;
}
PassOwnPtr<Vector<char>> PictureSnapshot::replay(unsigned fromStep, unsigned toStep, double scale) const
{
    const SkIRect bounds = m_picture->cullRect().roundOut();

    // TODO(fmalita): convert this to SkSurface/SkImage, drop the intermediate SkBitmap.
    SkBitmap bitmap;
    bitmap.allocPixels(SkImageInfo::MakeN32Premul(bounds.width(), bounds.height()));
    bitmap.eraseARGB(0, 0, 0, 0);
    {
        ReplayingCanvas canvas(bitmap, fromStep, toStep);
        // Disable LCD text preemptively, because the picture opacity is unknown.
        // The canonical API involves SkSurface props, but since we're not SkSurface-based
        // at this point (see TODO above) we (ab)use saveLayer for this purpose.
        SkAutoCanvasRestore autoRestore(&canvas, false);
        canvas.saveLayer(nullptr, nullptr);

        canvas.scale(scale, scale);
        canvas.resetStepCount();
        m_picture->playback(&canvas, &canvas);
    }
    OwnPtr<Vector<char>> base64Data = adoptPtr(new Vector<char>());
    Vector<char> encodedImage;

    RefPtr<SkImage> image = adoptRef(SkImage::NewFromBitmap(bitmap));
    if (!image)
        return nullptr;

    ImagePixelLocker pixelLocker(image, kUnpremul_SkAlphaType, kRGBA_8888_SkColorType);
    ImageDataBuffer imageData(IntSize(image->width(), image->height()),
        static_cast<const unsigned char*>(pixelLocker.pixels()));
    if (!PNGImageEncoder::encode(imageData, reinterpret_cast<Vector<unsigned char>*>(&encodedImage)))
        return nullptr;

    base64Encode(encodedImage, *base64Data);
    return base64Data.release();
}
示例#14
0
void PictureShape::paint(QPainter &painter, const KoViewConverter &converter,
                         KoShapePaintingContext &paintContext)
{
    Q_UNUSED(paintContext);

    QRectF viewRect = converter.documentToView(QRectF(QPointF(0,0), size()));
    if (imageData() == 0) {
        painter.fillRect(viewRect, QColor(Qt::gray));
        return;
    }

    painter.save();
    applyConversion(painter, converter);
    paintBorder(painter, converter);
    painter.restore();

    QSize pixmapSize = calcOptimalPixmapSize(viewRect.size(), imageData()->image().size());

    // Normalize the clipping rect if it isn't already done.
    m_clippingRect.normalize(imageData()->imageSize());

    // Handle style:mirror, i.e. mirroring horizontally and/or vertically.
    // 
    // NOTE: At this time we don't handle HorizontalOnEven
    //       and HorizontalOnOdd, which have to know which
    //       page they are on.  In those cases we treat it as
    //       no horizontal mirroring at all.
    bool   doFlip = false;
    QSizeF shapeSize = size();
    QSizeF viewSize = converter.documentToView(shapeSize);
    qreal  midpointX = 0.0;
    qreal  midpointY = 0.0;
    qreal  scaleX = 1.0;
    qreal  scaleY = 1.0;
    if (m_mirrorMode & MirrorHorizontal) {
        midpointX = viewSize.width() / qreal(2.0);
        scaleX = -1.0;
        doFlip = true;
    }
    if (m_mirrorMode & MirrorVertical) {
        midpointY = viewSize.height() / qreal(2.0);
        scaleY = -1.0;
        doFlip = true;
    }
    if (doFlip) {
        QTransform outputTransform = painter.transform();
        QTransform worldTransform  = QTransform();

        //kDebug(31000) << "Flipping" << midpointX << midpointY << scaleX << scaleY;
        worldTransform.translate(midpointX, midpointY);
        worldTransform.scale(scaleX, scaleY);
        worldTransform.translate(-midpointX, -midpointY);
        //kDebug(31000) << "After flipping for window" << worldTransform;

        QTransform newTransform = worldTransform * outputTransform;
        painter.setWorldTransform(newTransform);
    }

    // Paint the image as prepared in waitUntilReady()
    if (!m_printQualityImage.isNull() && pixmapSize != m_printQualityRequestedSize) {
        QSizeF imageSize = m_printQualityImage.size();
        QRectF cropRect(
            imageSize.width()  * m_clippingRect.left,
            imageSize.height() * m_clippingRect.top,
            imageSize.width()  * m_clippingRect.width(),
            imageSize.height() * m_clippingRect.height()
        );

        painter.drawImage(viewRect, m_printQualityImage, cropRect);
        m_printQualityImage = QImage(); // free memory
    }
    else {
        QPixmap pixmap;
        QString key(generate_key(imageData()->key(), pixmapSize));

        // If the required pixmap is not in the cache
        // launch a task in a background thread that scales
        // the source image to the required size
        if (!QPixmapCache::find(key, &pixmap)) {
            QThreadPool::globalInstance()->start(new _Private::PixmapScaler(this, pixmapSize));
            painter.fillRect(viewRect, QColor(Qt::gray)); // just paint a gray rect as long as we don't have the required pixmap
        }
        else {
            QRectF cropRect(
                pixmapSize.width()  * m_clippingRect.left,
                pixmapSize.height() * m_clippingRect.top,
                pixmapSize.width()  * m_clippingRect.width(),
                pixmapSize.height() * m_clippingRect.height()
            );

            painter.drawPixmap(viewRect, pixmap, cropRect);
        }
    }
}
示例#15
0
文件: pgfloader.cpp 项目: KDE/digikam
bool PGFLoader::load(const QString& filePath, DImgLoaderObserver* const observer)
{
    m_observer = observer;
    readMetadata(filePath, DImg::PGF);

    FILE* file = fopen(QFile::encodeName(filePath).constData(), "rb");

    if (!file)
    {
        qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Error: Could not open source file.";
        loadingFailed();
        return false;
    }

    unsigned char header[3];

    if (fread(&header, 3, 1, file) != 1)
    {
        fclose(file);
        loadingFailed();
        return false;
    }

    unsigned char pgfID[3] = { 0x50, 0x47, 0x46 };

    if (memcmp(&header[0], &pgfID, 3) != 0)
    {
        // not a PGF file
        fclose(file);
        loadingFailed();
        return false;
    }

    fclose(file);

    // -------------------------------------------------------------------
    // Initialize PGF API.

#ifdef WIN32
#ifdef UNICODE
    HANDLE fd = CreateFile((LPCWSTR)(QFile::encodeName(filePath).constData()), GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
#else
    HANDLE fd = CreateFile(QFile::encodeName(filePath).constData(), GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
#endif

    if (fd == INVALID_HANDLE_VALUE)
    {
        loadingFailed();
        return false;
    }

#else

    int fd = open(QFile::encodeName(filePath).constData(), O_RDONLY);

    if (fd == -1)
    {
        loadingFailed();
        return false;
    }

#endif

    CPGFFileStream stream(fd);
    CPGFImage      pgf;
    int            colorModel = DImg::COLORMODELUNKNOWN;

    try
    {
        // open pgf image
        pgf.Open(&stream);

        switch (pgf.Mode())
        {
            case ImageModeRGBColor:
            case ImageModeRGB48:
                m_hasAlpha = false;
                colorModel = DImg::RGB;
                break;

            case ImageModeRGBA:
                m_hasAlpha = true;
                colorModel = DImg::RGB;
                break;

            default:
                qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Cannot load PGF image: color mode not supported (" << pgf.Mode() << ")";
                loadingFailed();
                return false;
                break;
        }

        switch (pgf.Channels())
        {
            case 3:
            case 4:
                break;

            default:
                qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Cannot load PGF image: color channels number not supported (" << pgf.Channels() << ")";
                loadingFailed();
                return false;
                break;
        }

        int bitDepth = pgf.BPP();

        switch (bitDepth)
        {
            case 24:    // RGB 8 bits.
            case 32:    // RGBA 8 bits.
                m_sixteenBit = false;
                break;

            case 48:    // RGB 16 bits.
            case 64:    // RGBA 16 bits.
                m_sixteenBit = true;
                break;

            default:
                qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Cannot load PGF image: color bits depth not supported (" << bitDepth << ")";
                loadingFailed();
                return false;
                break;
        }

        if(DIGIKAM_DIMG_LOG_PGF().isDebugEnabled()) {
            const PGFHeader* header = pgf.GetHeader();
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF width    = " << header->width;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF height   = " << header->height;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF bbp      = " << header->bpp;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF channels = " << header->channels;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF quality  = " << header->quality;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF mode     = " << header->mode;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "Has Alpha    = " << m_hasAlpha;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "Is 16 bits   = " << m_sixteenBit;
        }

        // NOTE: see bug #273765 : Loading PGF thumbs with OpenMP support through a separated thread do not work properlly with libppgf 6.11.24
        pgf.ConfigureDecoder(false);

        int width   = pgf.Width();
        int height  = pgf.Height();
        uchar* data = 0;

        QSize originalSize(width, height);

        if (m_loadFlags & LoadImageData)
        {
            // -------------------------------------------------------------------
            // Find out if we do the fast-track loading with reduced size. PGF specific.
            int level          = 0;
            QVariant attribute = imageGetAttribute(QLatin1String("scaledLoadingSize"));

            if (attribute.isValid() && pgf.Levels() > 0)
            {
                int scaledLoadingSize = attribute.toInt();
                int i, w, h;

                for (i = pgf.Levels() - 1 ; i >= 0 ; --i)
                {
                    w = pgf.Width(i);
                    h = pgf.Height(i);

                    if (qMin(w, h) >= scaledLoadingSize)
                    {
                        break;
                    }
                }

                if (i >= 0)
                {
                    width  = w;
                    height = h;
                    level  = i;
                    qCDebug(DIGIKAM_DIMG_LOG_PGF) << "Loading PGF scaled version at level " << i
                                      << " (" << w << " x " << h << ") for size "
                                      << scaledLoadingSize;
                }
            }

            if (m_sixteenBit)
            {
                data = new_failureTolerant(width, height, 8); // 16 bits/color/pixel
            }
            else
            {
                data = new_failureTolerant(width, height, 4); // 8 bits/color/pixel
            }

            // Fill all with 255 including alpha channel.
            memset(data, 0xFF, width * height * (m_sixteenBit ? 8 : 4));

            pgf.Read(level, CallbackForLibPGF, this);
            pgf.GetBitmap(m_sixteenBit ? width * 8 : width * 4,
                          (UINT8*)data,
                          m_sixteenBit ? 64 : 32,
                          NULL,
                          CallbackForLibPGF, this);

            if (observer)
            {
                observer->progressInfo(m_image, 1.0);
            }
        }

        // -------------------------------------------------------------------
        // Get ICC color profile.

        if (m_loadFlags & LoadICCData)
        {
            // TODO: Implement proper storage in PGF for color profiles
            checkExifWorkingColorSpace();
        }

        imageWidth()  = width;
        imageHeight() = height;
        imageData()   = data;
        imageSetAttribute(QLatin1String("format"),             QLatin1String("PGF"));
        imageSetAttribute(QLatin1String("originalColorModel"), colorModel);
        imageSetAttribute(QLatin1String("originalBitDepth"),   bitDepth);
        imageSetAttribute(QLatin1String("originalSize"),       originalSize);

#ifdef WIN32
        CloseHandle(fd);
#else
        close(fd);
#endif

        return true;
    }
    catch (IOException& e)
    {
        int err = e.error;

        if (err >= AppError)
        {
            err -= AppError;
        }

        qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Error: Opening and reading PGF image failed (" << err << ")!";

#ifdef WIN32
        CloseHandle(fd);
#else
        close(fd);
#endif

        loadingFailed();
        return false;
    }
    catch (std::bad_alloc& e)
    {
        qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Failed to allocate memory for loading" << filePath << e.what();

#ifdef WIN32
        CloseHandle(fd);
#else
        close(fd);
#endif

        loadingFailed();
        return false;
    }
    return true;
}
示例#16
0
文件: pgfloader.cpp 项目: KDE/digikam
bool PGFLoader::save(const QString& filePath, DImgLoaderObserver* const observer)
{
    m_observer = observer;

#ifdef WIN32
#ifdef UNICODE
    HANDLE fd = CreateFile((LPCWSTR)(QFile::encodeName(filePath).constData()), GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
#else
    HANDLE fd = CreateFile(QFile::encodeName(filePath).constData(), GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
#endif

    if (fd == INVALID_HANDLE_VALUE)
    {
        qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Error: Could not open destination file.";
        return false;
    }

#elif defined(__POSIX__)
    int fd = open(QFile::encodeName(filePath).constData(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

    if (fd == -1)
    {
        qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Error: Could not open destination file.";
        return false;
    }

#endif

    try
    {
        QVariant qualityAttr = imageGetAttribute(QLatin1String("quality"));
        int quality          = qualityAttr.isValid() ? qualityAttr.toInt() : 3;

        qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF quality: " << quality;

        CPGFFileStream stream(fd);
        CPGFImage      pgf;
        PGFHeader      header;
        header.width   = imageWidth();
        header.height  = imageHeight();
        header.quality = quality;

        if (imageHasAlpha())
        {
            if (imageSixteenBit())
            {
                // NOTE : there is no PGF color mode in 16 bits with alpha.
                header.channels = 3;
                header.bpp      = 48;
                header.mode     = ImageModeRGB48;
            }
            else
            {
                header.channels = 4;
                header.bpp      = 32;
                header.mode     = ImageModeRGBA;
            }
        }
        else
        {
            if (imageSixteenBit())
            {
                header.channels = 3;
                header.bpp      = 48;
                header.mode     = ImageModeRGB48;
            }
            else
            {
                header.channels = 3;
                header.bpp      = 24;
                header.mode     = ImageModeRGBColor;
            }
        }

#ifdef PGFCodecVersionID
#   if PGFCodecVersionID < 0x061142
        header.background.rgbtBlue  = 0;
        header.background.rgbtGreen = 0;
        header.background.rgbtRed   = 0;
#   endif
#endif

        pgf.SetHeader(header);

        // NOTE: see bug #273765 : Loading PGF thumbs with OpenMP support through a separated thread do not work properlly with libppgf 6.11.24
        pgf.ConfigureEncoder(false);

        pgf.ImportBitmap(4 * imageWidth() * (imageSixteenBit() ? 2 : 1),
                         (UINT8*)imageData(),
                         imageBitsDepth() * 4,
                         NULL,
                         CallbackForLibPGF, this);

        UINT32 nWrittenBytes = 0;

#ifdef PGFCodecVersionID
#   if PGFCodecVersionID >= 0x061124
        pgf.Write(&stream, &nWrittenBytes, CallbackForLibPGF, this);
#   endif
#else
        pgf.Write(&stream, 0, CallbackForLibPGF, &nWrittenBytes, this);
#endif

        qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF width     = " << header.width;
        qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF height    = " << header.height;
        qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF bbp       = " << header.bpp;
        qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF channels  = " << header.channels;
        qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF quality   = " << header.quality;
        qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF mode      = " << header.mode;
        qCDebug(DIGIKAM_DIMG_LOG_PGF) << "Bytes Written = " << nWrittenBytes;

#ifdef WIN32
        CloseHandle(fd);
#else
        close(fd);
#endif
        // TODO: Store ICC profile in an appropriate place in the image
        storeColorProfileInMetadata();

        if (observer)
        {
            observer->progressInfo(m_image, 1.0);
        }

        imageSetAttribute(QLatin1String("savedformat"), QLatin1String("PGF"));
        saveMetadata(filePath);

        return true;
    }
    catch (IOException& e)
    {
        int err = e.error;

        if (err >= AppError)
        {
            err -= AppError;
        }

        qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Error: Opening and saving PGF image failed (" << err << ")!";

#ifdef WIN32
        CloseHandle(fd);
#else
        close(fd);
#endif

        return false;
    }
    return true;
}
示例#17
0
//-----------------------------------------------------------------------------
//Function Name : TInt SearchSymbolByLoadordering(TE32ExpSymInfoHdr* symInfoHeader
//							, char* aFileName, const char* aName, 
//							RPointerArray<TE32ExpSymInfoHdr>& aSearchedDlls,
//							void*& aSymAddress)
//Description   : To search for symbol named name in statically dependent dll 
//				  on aSymInfoHeader, it may be belonging to EXE or a DLL, also 
//				  dependencies of dependencies using Load-ordering. It also sets
//				  valid address in aSymAddress if name found, and all sll it searched in 
//				  aSearchedDlls param.	
//Return Value  : KErrNone if symbol found otherwise system wide error codes.
//-----------------------------------------------------------------------------
TInt SearchSymbolByLoadordering(const TE32ExpSymInfoHdr* symInfoHeader, const char* aFileName,
							    const char* aName,
							    RPointerArray<TE32ExpSymInfoHdr>& aSearchedDlls,
							    void*& aSymAddress)
	{
	//This is used as stack for Load-ordering or Depthfirst search.
	RArray<TImageData> dependentDllStack;
	//here on emulator we need two things one is Name to find symbol in that list,
	//second is TE32ExpSymInfoHdr to find dependencies
	TImageData imageData((char*)aFileName, (TE32ExpSymInfoHdr*)symInfoHeader);
	aSymAddress = NULL;
	//Add exe on the stack
	TInt err = dependentDllStack.Append(imageData);
	if ( KErrNone != err )
		{
		dependentDllStack.Close();
		return KErrNoMemory;
		}

	TE32ExpSymInfoHdr* tempSymInfoHeader = NULL;
	TInt lastIdx = 0;
	char* curDll = NULL;
	char* dependentDll = NULL;
	HMODULE handleToDll = NULL;
	TPtrC8 tempPtr;
	TBuf<KMaxFileName> dependentfileName;
	//Retunn address would be stored in this
	void* symAddr = NULL;
	//user to maintain load ordering
	RArray<TImageData> curDependentDll;
	TImageData tempImageData;
	//Depth First search for Load-ordering.
	while ( lastIdx >= 0 )
		{
		//Take first dll on the stack i.e. topmost
	    imageData = dependentDllStack[lastIdx];
	    symInfoHeader = imageData.iSymInfoHeader;
		//Remove from stack
	    dependentDllStack.Remove(lastIdx);

	    if(!symInfoHeader)
	    	{
	    	//skip non-std binaries...
		    lastIdx = dependentDllStack.Count() - 1;
	    	continue;
	    	}

		curDll = imageData.iFileName;
	 	tempPtr.Set((unsigned char*)curDll, strlen(curDll));
		dependentfileName.Copy(tempPtr);
		TParsePtr pParser(dependentfileName);
		dependentfileName = pParser.NameAndExt();
	  	//Search in this dll's symbol table	
		handleToDll = Emulator::GetModuleHandle(dependentfileName.PtrZ());
		symAddr = Emulator::GetProcAddress(handleToDll,aName);
		//Check if Symbol is found
		if( symAddr )
			{
			dependentDllStack.Close();
			aSymAddress = symAddr;
			return KErrNone;
			}
		//Add this dll to list of searched dlls
		err = aSearchedDlls.Append(symInfoHeader);
		if ( KErrNone != err )
			{
			dependentDllStack.Close();
			return KErrNoMemory;
			}
		dependentDll = (char*) symInfoHeader + sizeof(TE32ExpSymInfoHdr);
	
		//if this image is an exe - the these would be some symbols
		if ( symInfoHeader->iSymCount )
			{//skip all symbol addresse
			char* curSymbolStr = dependentDll + (KFourByteOffset * symInfoHeader->iSymCount);
			//skip all symbol names
			for (TInt i = 0; i < symInfoHeader->iSymCount; ++i )
				{
				curSymbolStr += strlen(curSymbolStr) + 1;
				}
			//initialise first dependent dll name	
			dependentDll = curSymbolStr;
			}
		//Store names of all dependent dlls of current dll/exe store there name in 
		//curDependentDll. This is done to maintain load ordering.
		for (TInt i = 0; i < symInfoHeader->iDllCount; ++i)
			{
			tempPtr.Set((unsigned char*)dependentDll, strlen(dependentDll));
			dependentfileName.Copy(tempPtr);
			handleToDll = Emulator::GetModuleHandle(dependentfileName.PtrZ());
			Emulator::TModule aModule((HINSTANCE)handleToDll);
			tempSymInfoHeader  = (TE32ExpSymInfoHdr*)aModule.Section(KWin32SectionName_NmdExpData);
			if ( tempSymInfoHeader && aSearchedDlls.Find(tempSymInfoHeader) == KErrNotFound )
				{
				tempImageData.iFileName = dependentDll;
				tempImageData.iSymInfoHeader = tempSymInfoHeader;
				err = curDependentDll.Append(tempImageData);
				if ( KErrNone != err )
					{
					dependentDllStack.Close();
					curDependentDll.Close();
					return KErrNoMemory;
					}
				}
			//advance to next dependent dll	
			dependentDll += tempPtr.Length() + 1;
			}
		//add in load order to dependentDllStack
		for (TInt i = curDependentDll.Count() - 1; i >= 0; --i)
			{
			err = dependentDllStack.Append(curDependentDll[i]);
			if ( KErrNone != err )
				{
				dependentDllStack.Close();
				curDependentDll.Close();
				return KErrNoMemory;
				}
			}
		curDependentDll.Close();	
		lastIdx = dependentDllStack.Count() - 1;	
		}
	dependentDllStack.Close();
	return KErrNotFound;
	}
// Main interface with NVTT
void NVTTProcessor::process( osg::Image& image, nvtt::Format format, bool generateMipMap, bool resizeToPowerOfTwo, CompressionMethod method, CompressionQuality quality)
{
    // Fill input options
    nvtt::InputOptions inputOptions;
    inputOptions.setTextureLayout(nvtt::TextureType_2D, image.s(), image.t() );
    inputOptions.setNormalMap(false);
    inputOptions.setConvertToNormalMap(false);
    inputOptions.setGamma(2.2f, 2.2f);
    inputOptions.setNormalizeMipmaps(false);
    inputOptions.setWrapMode(nvtt::WrapMode_Clamp);
    if (resizeToPowerOfTwo)
    {
        inputOptions.setRoundMode(nvtt::RoundMode_ToNearestPowerOfTwo);
    }
    inputOptions.setMipmapGeneration(generateMipMap);

    if (image.getPixelFormat() == GL_RGBA)
    {
        inputOptions.setAlphaMode( nvtt::AlphaMode_Transparency );
    }
    else
    {
        inputOptions.setAlphaMode( nvtt::AlphaMode_None );
    }
    std::vector<unsigned char> imageData( image.s() * image.t() * 4 );
    if (image.getPixelFormat() == GL_RGB)
    {
        convertRGBToBGRA( imageData, image );
    }
    else
    {
        convertRGBAToBGRA( imageData, image );
    }
    inputOptions.setMipmapData(&imageData[0],image.s(),image.t());

    // Fill compression options
    nvtt::CompressionOptions compressionOptions;
    switch(quality)
    {
      case FASTEST:
        compressionOptions.setQuality( nvtt::Quality_Fastest );
        break;
      case NORMAL:
        compressionOptions.setQuality( nvtt::Quality_Normal );
        break;
      case PRODUCTION:
        compressionOptions.setQuality( nvtt::Quality_Production);
        break;
      case HIGHEST:
        compressionOptions.setQuality( nvtt::Quality_Highest);
        break;
    }
    compressionOptions.setFormat( format );
    //compressionOptions.setQuantization(false,false,false);
    if (format == nvtt::Format_RGBA)
    {
        if (image.getPixelFormat() == GL_RGB)
        {
            compressionOptions.setPixelFormat(24,0xff,0xff00,0xff0000,0);
        }
        else
        {
            compressionOptions.setPixelFormat(32,0xff,0xff00,0xff0000,0xff000000);
        }
    }

    // Handler
    OSGImageOutputHandler outputHandler(format,image.getPixelFormat() == GL_RGB);
    VPBErrorHandler errorHandler;

    // Fill output options
    nvtt::OutputOptions outputOptions;
    outputOptions.setOutputHandler(&outputHandler);
    outputOptions.setErrorHandler(&errorHandler);
    outputOptions.setOutputHeader(false);

    // Process the compression now
    nvtt::Compressor compressor;
    if(method == USE_GPU)
    {
        compressor.enableCudaAcceleration(true);
        if(!compressor.isCudaAccelerationEnabled())
        {
            OSG_WARN<< "CUDA acceleration was enabled but it is not available. CPU will be used."<<std::endl;
        }
    }
    else
    {
        compressor.enableCudaAcceleration(false);
    }

    compressor.process(inputOptions,compressionOptions,outputOptions);

    outputHandler.assignImage(image);
}
示例#19
0
 virtual bool writePng(const char* filename) const
 {
     ScopedDataPng imageData(im_);
     return writeScopedData(filename, imageData);
 }
示例#20
0
ImageExtent ImageDataObject::extent()
{
    assert(ImageExtent(m_extent) == ImageExtent(imageData().GetExtent()));
    return ImageExtent(m_extent);
}
示例#21
0
KisImageBuilder_Result PSDLoader::decode(const KUrl& uri)
{
    // open the file
    QFile f(uri.toLocalFile());
    if (!f.exists()) {
        return KisImageBuilder_RESULT_NOT_EXIST;
    }
    if (!f.open(QIODevice::ReadOnly)) {
        return KisImageBuilder_RESULT_FAILURE;
    }

    dbgFile << "pos:" << f.pos();

    PSDHeader header;
    if (!header.read(&f)) {
        dbgFile << "failed reading header: " << header.error;
        return KisImageBuilder_RESULT_FAILURE;
    }

    dbgFile << header;
    dbgFile << "Read header. pos:" << f.pos();

    PSDColorModeBlock colorModeBlock(header.colormode);
    if (!colorModeBlock.read(&f)) {
        dbgFile << "failed reading colormode block: " << colorModeBlock.error;
        return KisImageBuilder_RESULT_FAILURE;
    }

    dbgFile << "Read color mode block. pos:" << f.pos();

    PSDResourceSection resourceSection;
    if (!resourceSection.read(&f)) {
        dbgFile << "failed reading resource section: " << resourceSection.error;
        return KisImageBuilder_RESULT_FAILURE;
    }

    dbgFile << "Read resource section. pos:" << f.pos();

    PSDLayerSection layerSection(header);
    if (!layerSection.read(&f)) {
        dbgFile << "failed reading layer section: " << layerSection.error;
        return KisImageBuilder_RESULT_FAILURE;
    }
    // XXX: add all the image resource blocks as annotations to the image

    dbgFile << "Read layer section. " << layerSection.nLayers << "layers. pos:" << f.pos();

    // Get the right colorspace
    QPair<QString, QString> colorSpaceId = psd_colormode_to_colormodelid(header.colormode,
                                                                         header.channelDepth);
    if (colorSpaceId.first.isNull()) return KisImageBuilder_RESULT_UNSUPPORTED_COLORSPACE;

    // Get the icc profile!
    const KoColorProfile* profile = 0;
    if (resourceSection.resources.contains(PSDResourceSection::ICC_PROFILE)) {
        ICC_PROFILE_1039 *iccProfileData = dynamic_cast<ICC_PROFILE_1039*>(resourceSection.resources[PSDResourceSection::ICC_PROFILE]->resource);
        if (iccProfileData ) {
            profile = KoColorSpaceRegistry::instance()->createColorProfile(colorSpaceId.first,
                                                                       colorSpaceId.second,
                                                                       iccProfileData->icc);
            dbgFile  << "Loaded ICC profile" << profile->name();
        }

    }

    // Create the colorspace
    const KoColorSpace* cs = KoColorSpaceRegistry::instance()->colorSpace(colorSpaceId.first, colorSpaceId.second, profile);
    if (!cs) {
        return KisImageBuilder_RESULT_UNSUPPORTED_COLORSPACE;
    }

    // Creating the KisImageWSP
    m_image = new KisImage(m_doc->createUndoStore(),  header.width, header.height, cs, "built image");
    Q_CHECK_PTR(m_image);
    m_image->lock();

    // set the correct resolution
    if (resourceSection.resources.contains(PSDResourceSection::RESN_INFO)) {
        RESN_INFO_1005 *resInfo = dynamic_cast<RESN_INFO_1005*>(resourceSection.resources[PSDResourceSection::RESN_INFO]->resource);
        if (resInfo) {
            m_image->setResolution(POINT_TO_INCH(resInfo->hRes), POINT_TO_INCH(resInfo->vRes));
            // let's skip the unit for now; we can only set that on the KoDocument, and krita doesn't use it.
        }
    }
    // Preserve the duotone colormode block for saving back to psd
    if (header.colormode == DuoTone) {
        KisAnnotationSP annotation = new KisAnnotation("DuotoneColormodeBlock",
                                                       i18n("Duotone Colormode Block"),
                                                       colorModeBlock.data);
        m_image->addAnnotation(annotation);
    }

    // read the projection into our single layer
    if (layerSection.nLayers == 0) {
        dbgFile << "Position" << f.pos() << "Going to read the projection into the first layer, which Photoshop calls 'Background'";

        KisPaintLayerSP layer = new KisPaintLayer(m_image, i18n("Background"), OPACITY_OPAQUE_U8);
        KisTransaction("", layer -> paintDevice());

        PSDImageData imageData(&header);
        imageData.read(&f, layer->paintDevice());

        //readLayerData(&f, layer->paintDevice(), f.pos(), QRect(0, 0, header.width, header.height));
        m_image->addNode(layer, m_image->rootLayer());

    }
    else {

        // read the channels for the various layers
        for(int i = 0; i < layerSection.nLayers; ++i) {

            // XXX: work out the group layer structure in Photoshop, as well as the adjustment layers

            PSDLayerRecord* layerRecord = layerSection.layers.at(i);
            dbgFile << "Going to read channels for layer" << i << layerRecord->layerName;

            KisPaintLayerSP layer = new KisPaintLayer(m_image, layerRecord->layerName, layerRecord->opacity);
            layer->setCompositeOp(psd_blendmode_to_composite_op(layerRecord->blendModeKey));
            if (!layerRecord->readPixelData(&f, layer->paintDevice())) {
                dbgFile << "failed reading channels for layer: " << layerRecord->layerName << layerRecord->error;
                return KisImageBuilder_RESULT_FAILURE;
            }

            m_image->addNode(layer, m_image->rootLayer());
            layer->setVisible(layerRecord->visible);
        }
    }

    m_image->unlock();
    return KisImageBuilder_RESULT_OK;
}
示例#22
0
bool JP2KLoader::save(const QString& filePath, DImgLoaderObserver* observer)
{
    FILE* file = fopen(QFile::encodeName(filePath), "wb");

    if (!file)
    {
        return false;
    }

    fclose(file);

    // -------------------------------------------------------------------
    // Initialize JPEG 2000 API.

    register long  i, x, y;
    unsigned long  number_components;

    jas_image_t*          jp2_image   = 0;
    jas_stream_t*         jp2_stream  = 0;
    jas_matrix_t*         pixels[4];
    jas_image_cmptparm_t  component_info[4];

    int init = jas_init();

    if (init != 0)
    {
        kDebug() << "Unable to init JPEG2000 decoder";
        return false;
    }

    jp2_stream = jas_stream_fopen(QFile::encodeName(filePath), "wb");

    if (jp2_stream == 0)
    {
        kDebug() << "Unable to open JPEG2000 stream";
        return false;
    }

    number_components = imageHasAlpha() ? 4 : 3;

    for (i = 0 ; i < (long)number_components ; ++i)
    {
        component_info[i].tlx    = 0;
        component_info[i].tly    = 0;
        component_info[i].hstep  = 1;
        component_info[i].vstep  = 1;
        component_info[i].width  = imageWidth();
        component_info[i].height = imageHeight();
        component_info[i].prec   = imageBitsDepth();
        component_info[i].sgnd   = false;
    }

    jp2_image = jas_image_create(number_components, component_info, JAS_CLRSPC_UNKNOWN);

    if (jp2_image == 0)
    {
        jas_stream_close(jp2_stream);
        kDebug() << "Unable to create JPEG2000 image";
        return false;
    }

    if (observer)
    {
        observer->progressInfo(m_image, 0.1F);
    }

    // -------------------------------------------------------------------
    // Check color space.

    if (number_components >= 3 )    // RGB & RGBA
    {
        // Alpha Channel
        if (number_components == 4 )
        {
            jas_image_setcmpttype(jp2_image, 3, JAS_IMAGE_CT_OPACITY);
        }

        jas_image_setclrspc(jp2_image, JAS_CLRSPC_SRGB);
        jas_image_setcmpttype(jp2_image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
        jas_image_setcmpttype(jp2_image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
        jas_image_setcmpttype(jp2_image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
    }

    // -------------------------------------------------------------------
    // Set ICC color profile.

    // FIXME : doesn't work yet!

    jas_cmprof_t*  cm_profile  = 0;
    jas_iccprof_t* icc_profile = 0;

    QByteArray profile_rawdata = m_image->getIccProfile().data();

    icc_profile = jas_iccprof_createfrombuf((uchar*)profile_rawdata.data(), profile_rawdata.size());

    if (icc_profile != 0)
    {
        cm_profile = jas_cmprof_createfromiccprof(icc_profile);

        if (cm_profile != 0)
        {
            jas_image_setcmprof(jp2_image, cm_profile);
        }
    }

    // -------------------------------------------------------------------
    // Convert to JPEG 2000 pixels.

    for (i = 0 ; i < (long)number_components ; ++i)
    {
        pixels[i] = jas_matrix_create(1, (unsigned int)imageWidth());

        if (pixels[i] == 0)
        {
            for (x = 0 ; x < i ; ++x)
            {
                jas_matrix_destroy(pixels[x]);
            }

            jas_image_destroy(jp2_image);
            kDebug() << "Error encoding JPEG2000 image data : Memory Allocation Failed";
            return false;
        }
    }

    unsigned char* data = imageData();
    unsigned char* pixel;
    unsigned short r, g, b, a=0;
    uint           checkpoint = 0;

    for (y = 0 ; y < (long)imageHeight() ; ++y)
    {
        if (observer && y == (long)checkpoint)
        {
            checkpoint += granularity(observer, imageHeight(), 0.8F);

            if (!observer->continueQuery(m_image))
            {
                jas_image_destroy(jp2_image);

                for (i = 0 ; i < (long)number_components ; ++i)
                {
                    jas_matrix_destroy(pixels[i]);
                }

                jas_cleanup();

                return false;
            }

            observer->progressInfo(m_image, 0.1 + (0.8 * ( ((float)y)/((float)imageHeight()) )));
        }

        for (x = 0 ; x < (long)imageWidth() ; ++x)
        {
            pixel = &data[((y * imageWidth()) + x) * imageBytesDepth()];

            if ( imageSixteenBit() )        // 16 bits image.
            {
                b = (unsigned short)(pixel[0]+256*pixel[1]);
                g = (unsigned short)(pixel[2]+256*pixel[3]);
                r = (unsigned short)(pixel[4]+256*pixel[5]);

                if (imageHasAlpha())
                {
                    a = (unsigned short)(pixel[6]+256*pixel[7]);
                }
            }
            else                            // 8 bits image.
            {
                b = (unsigned short)pixel[0];
                g = (unsigned short)pixel[1];
                r = (unsigned short)pixel[2];

                if (imageHasAlpha())
                {
                    a = (unsigned short)(pixel[3]);
                }
            }

            jas_matrix_setv(pixels[0], x, r);
            jas_matrix_setv(pixels[1], x, g);
            jas_matrix_setv(pixels[2], x, b);

            if (number_components > 3)
            {
                jas_matrix_setv(pixels[3], x, a);
            }
        }

        for (i = 0 ; i < (long)number_components ; ++i)
        {
            int ret = jas_image_writecmpt(jp2_image, (short) i, 0, (unsigned int)y,
                                          (unsigned int)imageWidth(), 1, pixels[i]);

            if (ret != 0)
            {
                kDebug() << "Error encoding JPEG2000 image data";

                jas_image_destroy(jp2_image);

                for (i = 0 ; i < (long)number_components ; ++i)
                {
                    jas_matrix_destroy(pixels[i]);
                }

                jas_cleanup();
                return false;
            }
        }
    }

    QVariant qualityAttr = imageGetAttribute("quality");
    int quality          = qualityAttr.isValid() ? qualityAttr.toInt() : 90;

    if (quality < 0)
    {
        quality = 90;
    }

    if (quality > 100)
    {
        quality = 100;
    }

    QString     rate;
    QTextStream ts( &rate, QIODevice::WriteOnly );

    // NOTE: to have a lossless compression use quality=100.
    // jp2_encode()::optstr:
    // - rate=#B => the resulting file size is about # bytes
    // - rate=0.0 .. 1.0 => the resulting file size is about the factor times
    //                      the uncompressed size
    ts << "rate=" << ( quality / 100.0F );

    kDebug() << "JPEG2000 quality: " << quality;
    kDebug() << "JPEG2000 " << rate;

    int ret = jp2_encode(jp2_image, jp2_stream, rate.toUtf8().data());

    if (ret != 0)
    {
        kDebug() << "Unable to encode JPEG2000 image";

        jas_image_destroy(jp2_image);
        jas_stream_close(jp2_stream);

        for (i = 0 ; i < (long)number_components ; ++i)
        {
            jas_matrix_destroy(pixels[i]);
        }

        jas_cleanup();

        return false;
    }

    if (observer)
    {
        observer->progressInfo(m_image, 1.0);
    }

    imageSetAttribute("savedformat", "JP2K");

    saveMetadata(filePath);

    jas_image_destroy(jp2_image);
    jas_stream_close(jp2_stream);

    for (i = 0 ; i < (long)number_components ; ++i)
    {
        jas_matrix_destroy(pixels[i]);
    }

    jas_cleanup();

    return true;
}
示例#23
0
int main(void) {
    GLFWwindow* window;
    glfwSetErrorCallback(error_callback);
    if (!glfwInit()) {
        exit(EXIT_FAILURE);
    }
    
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_SRGB_CAPABLE, GL_TRUE);
    
    window = glfwCreateWindow(kWidth, kHeight, "Simple example", NULL, NULL);
    if (!window) {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    
    init_skia(kWidth, kHeight);
    
    SkAutoTUnref<SkImage> atlas;
    SkRSXform   xform[kGrid*kGrid+1];
    SkRect      tex[kGrid*kGrid+1];
    WallTimer   timer;
    float       times[32];
    int         currentTime;

    SkAutoTUnref<SkData> imageData(SkData::NewFromFileName("ship.png"));
    atlas.reset(SkImage::NewFromEncoded(imageData));
    if (!atlas) {
        SkDebugf("\nCould not decode file ship.png\n");
        
        cleanup_skia();
        glfwDestroyWindow(window);
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    
    SkScalar anchorX = atlas->width()*0.5f;
    SkScalar anchorY = atlas->height()*0.5f;
    int currIndex = 0;
    for (int x = 0; x < kGrid; x++) {
        for (int y = 0; y < kGrid; y++) {
            float xPos = (x / (kGrid - 1.0)) * kWidth;
            float yPos = (y / (kGrid - 1.0)) * kWidth;
            
            tex[currIndex] = SkRect::MakeLTRB(0.0f, 0.0f, atlas->width(), atlas->height());
            xform[currIndex] = SkRSXform::MakeFromRadians(2.0f, SK_ScalarPI*0.5f,
                                                          xPos, yPos, anchorX, anchorY);
            currIndex++;
        }
    }
    tex[currIndex] = SkRect::MakeLTRB(0.0f, 0.0f, atlas->width(), atlas->height());
    xform[currIndex] = SkRSXform::MakeFromRadians(2.0f, SK_ScalarPI*0.5f,
                                                  kWidth*0.5f, kHeight*0.5f, anchorX, anchorY);
    
    currentTime = 0;
    
    glfwSwapInterval(1);
    glfwSetKeyCallback(window, key_callback);
    
    // Draw to the surface via its SkCanvas.
    SkCanvas* canvas = sSurface->getCanvas();   // We don't manage this pointer's lifetime.
    SkPaint paint;
    paint.setFilterQuality(kLow_SkFilterQuality);
    paint.setColor(SK_ColorWHITE);
    paint.setTextSize(15.0f);

    while (!glfwWindowShouldClose(window)) {
        const float kCosDiff = 0.99984769515f;
        const float kSinDiff = 0.01745240643f;

        timer.start();
        
        glfwPollEvents();
        
        float meanTime = 0.0f;
        for (int i = 0; i < 32; ++i) {
            meanTime += times[i];
        }
        meanTime /= 32.f;
        char outString[64];
        float fps = 1000.f/meanTime;
        sprintf(outString, "fps: %f ms: %f", fps, meanTime);
        
        for (int i = 0; i < kGrid*kGrid+1; ++i) {
            SkScalar c = xform[i].fSCos;
            SkScalar s = xform[i].fSSin;
        
            SkScalar dx = c*anchorX - s*anchorY;
            SkScalar dy = s*anchorX + c*anchorY;

            xform[i].fSCos = kCosDiff*c - kSinDiff*s;
            xform[i].fSSin = kSinDiff*c + kCosDiff*s;
            
            dx -= xform[i].fSCos*anchorX - xform[i].fSSin*anchorY;
            dy -= xform[i].fSSin*anchorX + xform[i].fSCos*anchorY;
            xform[i].fTx += dx;
            xform[i].fTy += dy;
        }
        
        canvas->clear(SK_ColorBLACK);
        canvas->drawAtlas(atlas, xform, tex, nullptr, kGrid*kGrid+1, SkXfermode::kSrcOver_Mode,
                          nullptr, &paint);
        canvas->drawText(outString, strlen(outString), 100.f, 100.f, paint);
        
        canvas->flush();
        
        timer.end();
        times[currentTime] = (float)(timer.fWall);
        currentTime = (currentTime + 1) & 0x1f;
        
        glfwSwapBuffers(window);
    }
  
    cleanup_skia();
    
    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
示例#24
0
bool JP2KLoader::load(const QString& filePath, DImgLoaderObserver* observer)
{
    readMetadata(filePath, DImg::JPEG);

    FILE* file = fopen(QFile::encodeName(filePath), "rb");

    if (!file)
    {
        loadingFailed();
        return false;
    }

    unsigned char header[9];

    if (fread(&header, 9, 1, file) != 1)
    {
        fclose(file);
        loadingFailed();
        return false;
    }

    unsigned char jp2ID[5] = { 0x6A, 0x50, 0x20, 0x20, 0x0D, };
    unsigned char jpcID[2] = { 0xFF, 0x4F };

    if (memcmp(&header[4], &jp2ID, 5) != 0 &&
        memcmp(&header,    &jpcID, 2) != 0)
    {
        // not a jpeg2000 file
        fclose(file);
        loadingFailed();
        return false;
    }

    fclose(file);

    imageSetAttribute("format", "JP2K");

    if (!(m_loadFlags & LoadImageData) && !(m_loadFlags & LoadICCData))
    {
        // libjasper will load the full image in memory already when calling jas_image_decode.
        // This is bad when scanning. See bugs 215458 and 195583.
        //FIXME: Use Exiv2 or OpenJPEG to extract this info
        DMetadata metadata(filePath);
        QSize size = metadata.getImageDimensions();

        if (size.isValid())
        {
            imageWidth() = size.width();
            imageHeight() = size.height();
        }

        return true;
    }

    // -------------------------------------------------------------------
    // Initialize JPEG 2000 API.

    register long  i, x, y;
    int            components[4];
    unsigned int   maximum_component_depth, scale[4], x_step[4], y_step[4];
    unsigned long  number_components;

    jas_image_t*  jp2_image   = 0;
    jas_stream_t* jp2_stream  = 0;
    jas_matrix_t* pixels[4];

    int init = jas_init();

    if (init != 0)
    {
        kDebug() << "Unable to init JPEG2000 decoder";
        loadingFailed();
        return false;
    }

    jp2_stream = jas_stream_fopen(QFile::encodeName(filePath), "rb");

    if (jp2_stream == 0)
    {
        kDebug() << "Unable to open JPEG2000 stream";
        loadingFailed();
        return false;
    }

    jp2_image = jas_image_decode(jp2_stream, -1, 0);

    if (jp2_image == 0)
    {
        jas_stream_close(jp2_stream);
        kDebug() << "Unable to decode JPEG2000 image";
        loadingFailed();
        return false;
    }

    jas_stream_close(jp2_stream);

    // some pseudo-progress
    if (observer)
    {
        observer->progressInfo(m_image, 0.1F);
    }

    // -------------------------------------------------------------------
    // Check color space.

    int colorModel;

    switch (jas_clrspc_fam(jas_image_clrspc(jp2_image)))
    {
        case JAS_CLRSPC_FAM_RGB:
        {
            components[0] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_RGB_R);
            components[1] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_RGB_G);
            components[2] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_RGB_B);

            if ((components[0] < 0) || (components[1] < 0) || (components[2] < 0))
            {
                jas_image_destroy(jp2_image);
                kDebug() << "Error parsing JPEG2000 image : Missing Image Channel";
                loadingFailed();
                return false;
            }

            number_components = 3;
            components[3]     = jas_image_getcmptbytype(jp2_image, 3);

            if (components[3] > 0)
            {
                m_hasAlpha = true;
                ++number_components;
            }

            colorModel = DImg::RGB;
            break;
        }
        case JAS_CLRSPC_FAM_GRAY:
        {
            components[0] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_GRAY_Y);

            if (components[0] < 0)
            {
                jas_image_destroy(jp2_image);
                kDebug() << "Error parsing JP2000 image : Missing Image Channel";
                loadingFailed();
                return false;
            }

            number_components = 1;
            colorModel        = DImg::GRAYSCALE;
            break;
        }
        case JAS_CLRSPC_FAM_YCBCR:
        {
            components[0] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_YCBCR_Y);
            components[1] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_YCBCR_CB);
            components[2] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_YCBCR_CR);

            if ((components[0] < 0) || (components[1] < 0) || (components[2] < 0))
            {
                jas_image_destroy(jp2_image);
                kDebug() << "Error parsing JP2000 image : Missing Image Channel";
                loadingFailed();
                return false;
            }

            number_components = 3;
            components[3]     = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_UNKNOWN);

            if (components[3] > 0)
            {
                m_hasAlpha = true;
                ++number_components;
            }

            // FIXME : image->colorspace=YCbCrColorspace;
            colorModel = DImg::YCBCR;
            break;
        }
        default:
        {
            jas_image_destroy(jp2_image);
            kDebug() << "Error parsing JP2000 image : Colorspace Model Is Not Supported";
            loadingFailed();
            return false;
        }
    }

    // -------------------------------------------------------------------
    // Check image geometry.

    imageWidth()  = jas_image_width(jp2_image);
    imageHeight() = jas_image_height(jp2_image);

    for (i = 0; i < (long)number_components; ++i)
    {
        if ((((jas_image_cmptwidth(jp2_image, components[i])*
               jas_image_cmpthstep(jp2_image, components[i])) != (long)imageWidth()))  ||
            (((jas_image_cmptheight(jp2_image, components[i])*
               jas_image_cmptvstep(jp2_image, components[i])) != (long)imageHeight())) ||
            (jas_image_cmpttlx(jp2_image, components[i]) != 0)                      ||
            (jas_image_cmpttly(jp2_image, components[i]) != 0)                      ||
            (jas_image_cmptsgnd(jp2_image, components[i]) != false))
        {
            jas_image_destroy(jp2_image);
            kDebug() << "Error parsing JPEG2000 image : Irregular Channel Geometry Not Supported";
            loadingFailed();
            return false;
        }

        x_step[i] = jas_image_cmpthstep(jp2_image, components[i]);
        y_step[i] = jas_image_cmptvstep(jp2_image, components[i]);
    }

    // -------------------------------------------------------------------
    // Get image format.

    m_hasAlpha              = number_components > 3;
    maximum_component_depth = 0;

    for (i = 0; i < (long)number_components; ++i)
    {
        maximum_component_depth = qMax((long)jas_image_cmptprec(jp2_image,components[i]),
                                       (long)maximum_component_depth);
        pixels[i] = jas_matrix_create(1, ((unsigned int)imageWidth())/x_step[i]);

        if (!pixels[i])
        {
            jas_image_destroy(jp2_image);
            kDebug() << "Error decoding JPEG2000 image data : Memory Allocation Failed";
            loadingFailed();
            return false;
        }
    }

    if (maximum_component_depth > 8)
    {
        m_sixteenBit = true;
    }

    for (i = 0 ; i < (long)number_components ; ++i)
    {
        scale[i] = 1;
        int prec = jas_image_cmptprec(jp2_image, components[i]);

        if (m_sixteenBit && prec < 16)
        {
            scale[i] = (1 << (16 - jas_image_cmptprec(jp2_image, components[i])));
        }
    }

    // -------------------------------------------------------------------
    // Get image data.

    uchar* data = 0;

    if (m_loadFlags & LoadImageData)
    {
        if (m_sixteenBit)          // 16 bits image.
        {
            data = new_failureTolerant(imageWidth()*imageHeight()*8);
        }
        else
        {
            data = new_failureTolerant(imageWidth()*imageHeight()*4);
        }

        if (!data)
        {
            kDebug() << "Error decoding JPEG2000 image data : Memory Allocation Failed";
            jas_image_destroy(jp2_image);

            for (i = 0 ; i < (long)number_components ; ++i)
            {
                jas_matrix_destroy(pixels[i]);
            }

            jas_cleanup();
            loadingFailed();
            return false;
        }

        uint   checkPoint     = 0;
        uchar* dst            = data;
        unsigned short* dst16 = (unsigned short*)data;

        for (y = 0 ; y < (long)imageHeight() ; ++y)
        {
            for (i = 0 ; i < (long)number_components; ++i)
            {
                int ret = jas_image_readcmpt(jp2_image, (short)components[i], 0,
                                             ((unsigned int) y)            / y_step[i],
                                             ((unsigned int) imageWidth()) / x_step[i],
                                             1, pixels[i]);

                if (ret != 0)
                {
                    kDebug() << "Error decoding JPEG2000 image data";
                    delete [] data;
                    jas_image_destroy(jp2_image);

                    for (i = 0 ; i < (long)number_components ; ++i)
                    {
                        jas_matrix_destroy(pixels[i]);
                    }

                    jas_cleanup();
                    loadingFailed();
                    return false;
                }
            }

            switch (number_components)
            {
                case 1: // Grayscale.
                {
                    for (x = 0 ; x < (long)imageWidth() ; ++x)
                    {
                        dst[0] = (uchar)(scale[0]*jas_matrix_getv(pixels[0], x/x_step[0]));
                        dst[1] = dst[0];
                        dst[2] = dst[0];
                        dst[3] = 0xFF;

                        dst += 4;
                    }

                    break;
                }
                case 3: // RGB.
                {
                    if (!m_sixteenBit)   // 8 bits image.
                    {
                        for (x = 0 ; x < (long)imageWidth() ; ++x)
                        {
                            // Blue
                            dst[0] = (uchar)(scale[2]*jas_matrix_getv(pixels[2], x/x_step[2]));
                            // Green
                            dst[1] = (uchar)(scale[1]*jas_matrix_getv(pixels[1], x/x_step[1]));
                            // Red
                            dst[2] = (uchar)(scale[0]*jas_matrix_getv(pixels[0], x/x_step[0]));
                            // Alpha
                            dst[3] = 0xFF;

                            dst += 4;
                        }
                    }
                    else                // 16 bits image.
                    {
                        for (x = 0 ; x < (long)imageWidth() ; ++x)
                        {
                            // Blue
                            dst16[0] = (unsigned short)(scale[2]*jas_matrix_getv(pixels[2], x/x_step[2]));
                            // Green
                            dst16[1] = (unsigned short)(scale[1]*jas_matrix_getv(pixels[1], x/x_step[1]));
                            // Red
                            dst16[2] = (unsigned short)(scale[0]*jas_matrix_getv(pixels[0], x/x_step[0]));
                            // Alpha
                            dst16[3] = 0xFFFF;

                            dst16 += 4;
                        }
                    }

                    break;
                }
                case 4: // RGBA.
                {
                    if (!m_sixteenBit)   // 8 bits image.
                    {
                        for (x = 0 ; x < (long)imageWidth() ; ++x)
                        {
                            // Blue
                            dst[0] = (uchar)(scale[2] * jas_matrix_getv(pixels[2], x/x_step[2]));
                            // Green
                            dst[1] = (uchar)(scale[1] * jas_matrix_getv(pixels[1], x/x_step[1]));
                            // Red
                            dst[2] = (uchar)(scale[0] * jas_matrix_getv(pixels[0], x/x_step[0]));
                            // Alpha
                            dst[3] = (uchar)(scale[3] * jas_matrix_getv(pixels[3], x/x_step[3]));

                            dst += 4;
                        }
                    }
                    else                // 16 bits image.
                    {
                        for (x = 0 ; x < (long)imageWidth() ; ++x)
                        {
                            // Blue
                            dst16[0] = (unsigned short)(scale[2]*jas_matrix_getv(pixels[2], x/x_step[2]));
                            // Green
                            dst16[1] = (unsigned short)(scale[1]*jas_matrix_getv(pixels[1], x/x_step[1]));
                            // Red
                            dst16[2] = (unsigned short)(scale[0]*jas_matrix_getv(pixels[0], x/x_step[0]));
                            // Alpha
                            dst16[3] = (unsigned short)(scale[3]*jas_matrix_getv(pixels[3], x/x_step[3]));

                            dst16 += 4;
                        }
                    }

                    break;
                }
            }

            // use 0-10% and 90-100% for pseudo-progress
            if (observer && y >= (long)checkPoint)
            {
                checkPoint += granularity(observer, y, 0.8F);

                if (!observer->continueQuery(m_image))
                {
                    delete [] data;
                    jas_image_destroy(jp2_image);

                    for (i = 0 ; i < (long)number_components ; ++i)
                    {
                        jas_matrix_destroy(pixels[i]);
                    }

                    jas_cleanup();

                    loadingFailed();
                    return false;
                }

                observer->progressInfo(m_image, 0.1 + (0.8 * ( ((float)y)/((float)imageHeight()) )));
            }
        }
    }

    // -------------------------------------------------------------------
    // Get ICC color profile.

    if (m_loadFlags & LoadICCData)
    {
        jas_iccprof_t* icc_profile = 0;
        jas_stream_t*  icc_stream  = 0;
        jas_cmprof_t*  cm_profile  = 0;

        cm_profile = jas_image_cmprof(jp2_image);

        if (cm_profile != 0)
        {
            icc_profile = jas_iccprof_createfromcmprof(cm_profile);
        }

        if (icc_profile != 0)
        {
            icc_stream = jas_stream_memopen(NULL, 0);

            if (icc_stream != 0)
            {
                if (jas_iccprof_save(icc_profile, icc_stream) == 0)
                {
                    if (jas_stream_flush(icc_stream) == 0)
                    {
                        jas_stream_memobj_t* blob = (jas_stream_memobj_t*) icc_stream->obj_;
                        QByteArray profile_rawdata;
                        profile_rawdata.resize(blob->len_);
                        memcpy(profile_rawdata.data(), blob->buf_, blob->len_);
                        imageSetIccProfile(profile_rawdata);
                        jas_stream_close(icc_stream);
                    }
                }
            }
        }
    }

    if (observer)
    {
        observer->progressInfo(m_image, 1.0);
    }

    imageData() = data;
    imageSetAttribute("format", "JP2K");
    imageSetAttribute("originalColorModel", colorModel);
    imageSetAttribute("originalBitDepth", maximum_component_depth);
    imageSetAttribute("originalSize", QSize(imageWidth(), imageHeight()));

    jas_image_destroy(jp2_image);

    for (i = 0 ; i < (long)number_components ; ++i)
    {
        jas_matrix_destroy(pixels[i]);
    }

    jas_cleanup();

    return true;
}
示例#25
0
QImage WinHelpPicture::LoadDDB(QIODevice &device,
    qint64 offset,
    size_t size,
    const BitmapHeader &hdr)
{
    seekFile(device, offset);
    if((hdr.getWidth() * hdr.getHeight()) > 100000000)
    {
        qDebug() << "Image is too large";
        QImage errorImg(100, 100, QImage::Format_ARGB32);
        QPainter painter;
        painter.begin(&errorImg);
        painter.fillRect(0, 0, 100, 100, Qt::white);
        painter.drawText(10, 10, "Image is too large");
        painter.end();
        return errorImg;
    }
    QImage image(hdr.getWidth(), hdr.getHeight(), QImage::Format_ARGB32);
    int colorsUsed = hdr.getColorsUsed();
    if(colorsUsed == 2)
    {
        size_t scanlineBytes =
            static_cast<size_t>(((hdr.getWidth() + 31) / 32) * 4);
        size_t imageSize = scanlineBytes * static_cast<size_t>(hdr.getHeight());
        if(imageSize > 0x40000000)
        {
            throw std::runtime_error("Requested too much memory for 1 bpp DDB");
        }
        QScopedArrayPointer<quint8> imageData(new quint8[imageSize]);
        memset(reinterpret_cast<void *>(imageData.data()), 0, imageSize);
        qint64 toRead = static_cast<qint64>(qMin(size, imageSize));
        fillBuffer(device, toRead,
            reinterpret_cast<void *>(imageData.data()), imageSize);
        quint8 masks[] = {
            128, 64, 32, 16, 8, 4, 2, 1
        };
        for (size_t row = 0; row < static_cast<size_t>(hdr.getHeight()); row++)
        {
            for (size_t col = 0; col < static_cast<size_t>(hdr.getWidth());
                col++)
            {
                if ((imageData[row * scanlineBytes + col /
                            8] & masks[col % 8]) != 0)
                {
                    image.setPixel(col, hdr.getHeight() - 1 - row,
                        qRgb(255, 255, 255));
                }
                else
                {
                    image.setPixel(col, hdr.getHeight() - 1 - row, qRgb(0, 0, 0));
                }
            }
        }
    }
    else
    {
        if(colorsUsed == 16)
        {
            size_t scanlineBytes =
                static_cast<size_t>(((hdr.getWidth() * 4 + 31) / 32) * 4);
            size_t imageSize = scanlineBytes *
                static_cast<size_t>(hdr.getHeight());
            if(imageSize > 0x40000000)
            {
                throw std::runtime_error(
                    "Requested too much memory for 4 bpp DDB");
            }
            QScopedArrayPointer<quint8> imageData(new quint8[imageSize]);
            memset(reinterpret_cast<void *>(imageData.data()), 0, imageSize);
            qint64 toRead = static_cast<qint64>(qMin(size, imageSize));
            fillBuffer(device, toRead,
                reinterpret_cast<void *>(imageData.data()), imageSize);
            for (size_t row = 0; row < static_cast<size_t>(hdr.getHeight());
                row++)
            {
                for (size_t col = 0; col < static_cast<size_t>(hdr.getWidth());
                    col++)
                {
                    quint8 colorIndex = 0;
                    if ((col & 1) == 0)
                    {
                        colorIndex = imageData[row * scanlineBytes + col / 2];
                        colorIndex = colorIndex >> 4;
                    }
                    else
                    {
                        colorIndex =
                            imageData[row * scanlineBytes + col / 2] & 15;
                    }
                    int color = qRound(
                            (static_cast<qreal>(colorIndex) / 15.0) * 255.0);
                    image.setPixel(col, hdr.getHeight() - 1 - row,
                        qRgb(color, color, color));
                }
            }
示例#26
0
ValueRange<> ImageDataObject::scalarRange()
{
    return ValueRange<>(imageData().GetScalarRange());
}
void RenderSVGResourceMasker::createMaskImage(MaskerData* maskerData, const SVGMaskElement* maskElement, RenderObject* object)
{
    FloatRect objectBoundingBox = object->objectBoundingBox();

    // Mask rect clipped with clippingBoundingBox and filterBoundingBox as long as they are present.
    maskerData->maskRect = object->repaintRectInLocalCoordinates();
    if (maskerData->maskRect.isEmpty()) {
        maskerData->emptyMask = true;
        return;
    }
    
    if (m_maskBoundaries.isEmpty())
        calculateMaskContentRepaintRect();

    FloatRect repaintRect = m_maskBoundaries;
    AffineTransform contextTransform;
    // We need to scale repaintRect for objectBoundingBox to get the drawing area.
    if (maskElement->maskContentUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
        contextTransform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
        FloatPoint contextAdjustment = repaintRect.location();
        repaintRect = contextTransform.mapRect(repaintRect);
        repaintRect.move(objectBoundingBox.x(), objectBoundingBox.y());
        contextTransform.translate(-contextAdjustment.x(), -contextAdjustment.y());
    }
    repaintRect.intersect(maskerData->maskRect);
    maskerData->maskRect = repaintRect;
    IntRect maskImageRect = enclosingIntRect(maskerData->maskRect);

    maskImageRect.setLocation(IntPoint());

    // Don't create ImageBuffers with image size of 0
    if (maskImageRect.isEmpty()) {
        maskerData->emptyMask = true;
        return;
    }

    // FIXME: This changes color space to linearRGB, the default color space
    // for masking operations in SVG. We need a switch for the other color-space
    // attribute values sRGB, inherit and auto.
    maskerData->maskImage = ImageBuffer::create(maskImageRect.size(), LinearRGB);
    if (!maskerData->maskImage)
        return;

    GraphicsContext* maskImageContext = maskerData->maskImage->context();
    ASSERT(maskImageContext);

    maskImageContext->save();

    if (maskElement->maskContentUnits() == SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
        maskImageContext->translate(-maskerData->maskRect.x(), -maskerData->maskRect.y());
    maskImageContext->concatCTM(contextTransform);

    // draw the content into the ImageBuffer
    for (Node* node = maskElement->firstChild(); node; node = node->nextSibling()) {
        RenderObject* renderer = node->renderer();
        if (!node->isSVGElement() || !static_cast<SVGElement*>(node)->isStyled() || !renderer)
            continue;
        RenderStyle* style = renderer->style();
        if (!style || style->display() == NONE || style->visibility() != VISIBLE)
            continue;
        renderSubtreeToImage(maskerData->maskImage.get(), renderer);
    }

    maskImageContext->restore();

    // create the luminance mask
    RefPtr<ImageData> imageData(maskerData->maskImage->getUnmultipliedImageData(maskImageRect));
    CanvasPixelArray* srcPixelArray(imageData->data());

    for (unsigned pixelOffset = 0; pixelOffset < srcPixelArray->length(); pixelOffset += 4) {
        unsigned char a = srcPixelArray->get(pixelOffset + 3);
        if (!a)
            continue;
        unsigned char r = srcPixelArray->get(pixelOffset);
        unsigned char g = srcPixelArray->get(pixelOffset + 1);
        unsigned char b = srcPixelArray->get(pixelOffset + 2);

        double luma = (r * 0.2125 + g * 0.7154 + b * 0.0721) * ((double)a / 255.0);
        srcPixelArray->set(pixelOffset + 3, luma);
    }

    maskerData->maskImage->putUnmultipliedImageData(imageData.get(), maskImageRect, IntPoint());
}
示例#28
0
//-----------------------------------------------------------------------------
//Function Name : void* DlSymByDependencyOrdering(const void* aHandle,
//													const char* aName)
//Description   : To search for symbol named name in statically dependent dll 
//				  on aSymInfoHeader, is dependencies, also dependencies of 
//				  dependencies using Dependency-ordering. 
//Return Value  : Valid address if name found otherwise NULL
//-----------------------------------------------------------------------------
void* DlSymByDependencyOrdering(const void* aHandle,const char* aName)
	{
	//Get 0th ordinal datastructure of dll denoted by handle.
	LoadedDlls()->Lock();
	TInt idx = LoadedDlls()->Find(aHandle);
	//check if handle not found	
	if ( KErrNotFound == idx )
		{
		LoadedDlls()->UnLock();
		SetError(KDlSymErrBadHandle);
		return NULL;
		}
	TDllEntry& dllEntry = LoadedDlls()->At(idx);
	
	// The below 'if' condition prevents the symbol lookup on non-STDDLL
	// Check for the symbol information, if not found
	// return with KDlSymErrNoSupport 
	if( !dllEntry.iSymbolHeader )
		{
		LoadedDlls()->UnLock();
		SetError(KDlSymErrNoSupport);
		return NULL;
		}

	TBuf8<KMaxFileName> fileName;
	if(CnvUtfConverter::ConvertFromUnicodeToUtf8(fileName,dllEntry.iLibrary.FileName()) != 0)
		{
		LoadedDlls()->UnLock();
		return NULL;
		}
	TE32ExpSymInfoHdr* symInfoHeader = dllEntry.iSymbolHeader;
	//Queue for using Breadthfirst search / Dependency ordering.
	RArray<TImageData> dependentDllQue;
	TImageData imageData((char*)fileName.PtrZ(), symInfoHeader);
	//add first item in queue
	TInt err = dependentDllQue.Append(imageData);
	if ( KErrNone != err )
		{
		LoadedDlls()->UnLock();
		dependentDllQue.Close();
		SetError(KDlSymErrNoMemory);	
		return NULL;		
		}
	char* curDll = NULL;
	char* dependentDll = NULL;
	HMODULE handleToDll = NULL;
	TBuf<KMaxFileName> dependentfileName;	
	TE32ExpSymInfoHdr* tempSymInfoHeader = NULL;
	void* symAddr = NULL;
	TPtrC8 tempPtr;
	//Array of searched dlls. Used to check circular dependency
	//this is array of pointer to name of dll in image
	RPointerArray<TE32ExpSymInfoHdr> searchedDlls;
	//Breath First search for Dependancy ordering.
	while(dependentDllQue.Count())
		{
		imageData = dependentDllQue[0];
		curDll = imageData.iFileName;
		symInfoHeader = imageData.iSymInfoHeader;
		dependentDllQue.Remove(0);
		
		// The below 'if' condition prevents the symbol lookup on dependent non-STDDLL
		if(!symInfoHeader)
			{
			continue;
			}

		tempPtr.Set((unsigned char*)curDll, strlen(curDll));
		dependentfileName.Copy(tempPtr);
		TParsePtr pParser(dependentfileName);
		dependentfileName = pParser.NameAndExt();
	  	//Search in this dll's symbol table	
		handleToDll = Emulator::GetModuleHandle(dependentfileName.PtrZ());
		symAddr = Emulator::GetProcAddress(handleToDll,aName);
		//check if symbol is found
		if( symAddr )
			{
			LoadedDlls()->UnLock();
			dependentDllQue.Close();
			searchedDlls.Close();
			return symAddr;
			}
		//Insert this to searched list
		err = searchedDlls.Append(symInfoHeader);
		if ( KErrNone != err )
			{
			LoadedDlls()->UnLock();
			dependentDllQue.Close();
			searchedDlls.Close();	
			SetError(KDlSymErrNoMemory);	
			return NULL;		
			}
		//Add list of dependencies
		dependentDll = (char*) symInfoHeader + sizeof(TE32ExpSymInfoHdr);

		//Add at last to make it Queue, needed for Dependency ordering
		for (TInt i = 0; i <  symInfoHeader->iDllCount; i++)
			{
			tempPtr.Set((unsigned char*)dependentDll, strlen(dependentDll));
			dependentfileName.Copy(tempPtr);
			//get i'th dependency
			handleToDll = Emulator::GetModuleHandle(dependentfileName.PtrZ());
			Emulator::TModule aModule((HINSTANCE)handleToDll);
			tempSymInfoHeader  = (TE32ExpSymInfoHdr*)aModule.Section(KWin32SectionName_NmdExpData);
			//check i'th dependency is OE dll e.i. equal to zero or not
			//and also its not already searched
			if ( tempSymInfoHeader && searchedDlls.Find(tempSymInfoHeader) == KErrNotFound )
				{
				imageData.iFileName = dependentDll;
				imageData.iSymInfoHeader = tempSymInfoHeader;
				err = dependentDllQue.Append(imageData);
				if ( KErrNone  != err )
					{
					LoadedDlls()->UnLock();
					dependentDllQue.Close();
					searchedDlls.Close();
					SetError(KDlSymErrNoMemory);	
					return NULL;		
					}
				}
			//advance to next dependent dll	
			dependentDll += tempPtr.Length() + 1;
			}
		}
	LoadedDlls()->UnLock();	
	dependentDllQue.Close();
	searchedDlls.Close();
	//Symbol not found return NULL
	SetError(KDlSymErrNotFound);
	return NULL;	
	}
示例#29
0
bool QImageLoader::load(const QString& filePath, DImgLoaderObserver* const observer)
{
    // Loading is opaque to us. No support for stopping from observer,
    // progress info are only pseudo values
    QImage image(filePath);

    if (observer)
    {
        observer->progressInfo(m_image, 0.9F);
    }

    if (image.isNull())
    {
        kDebug() << "Can not load \"" << filePath << "\" using DImg::QImageLoader!";
        loadingFailed();
        return false;
    }

    int colorModel    = DImg::COLORMODELUNKNOWN;
    int originalDepth = 0;

    switch (image.format())
    {
        case QImage::Format_Invalid:
        default:
            colorModel = DImg::COLORMODELUNKNOWN;
            originalDepth = 0;
            break;

        case QImage::Format_Mono:
        case QImage::Format_MonoLSB:
            colorModel = DImg::MONOCHROME;
            originalDepth = 1;
            break;

        case QImage::Format_Indexed8:
            colorModel = DImg::INDEXED;
            originalDepth = 0;
            break;

        case QImage::Format_RGB32:
            colorModel = DImg::RGB;
            originalDepth = 8;
            break;

        case QImage::Format_ARGB32:
        case QImage::Format_ARGB32_Premultiplied:
            colorModel = DImg::RGB;
            originalDepth = 8;
            break;
    }

    m_hasAlpha        = image.hasAlphaChannel();
    QImage target     = image.convertToFormat(QImage::Format_ARGB32);
    uint w            = target.width();
    uint h            = target.height();
    uchar* const data = new_failureTolerant(w, h, 4);

    if (!data)
    {
        kDebug() << "Failed to allocate memory for loading" << filePath;
        loadingFailed();
        return false;
    }

    uint*  sptr = reinterpret_cast<uint*>(target.bits());
    uchar* dptr = data;

    for (uint i = 0 ; i < w * h ; ++i)
    {
        dptr[0] = qBlue(*sptr);
        dptr[1] = qGreen(*sptr);
        dptr[2] = qRed(*sptr);
        dptr[3] = qAlpha(*sptr);

        dptr += 4;
        sptr++;
    }

    if (observer)
    {
        observer->progressInfo(m_image, 1.0);
    }

    imageWidth()  = w;
    imageHeight() = h;
    imageData()   = data;

    // We considering that PNG is the most representative format of an image loaded by Qt
    imageSetAttribute("format", "PNG");
    imageSetAttribute("originalColorModel", colorModel);
    imageSetAttribute("originalBitDepth", originalDepth);
    imageSetAttribute("originalSize", QSize(w, h));

    return true;
}
示例#30
0
void windowManager::openProject() {

  //const QString fileString = "test.out";
  const QString fileString =
    QFileDialog::getOpenFileName(activeWindow(), tr("Open project"), ".",
                                 "Cstitch files (*.xst)\nAll files (*.*)");
  if (fileString.isEmpty()) {
    return;
  }

  QFile inFile(fileString);
  inFile.open(QIODevice::ReadOnly);
  // the save file starts with xml text, so read that first
  QTextStream textInStream(&inFile);
  QString inString;
  inString = textInStream.readLine() + "\n";
  // (A day after the initial release I changed the program name from
  // stitch to cstitch, so check for either...)
  QRegExp rx("^<(cstitch|stitch) version=");
  rx.indexIn(inString);
  const QString programName = rx.cap(1);
  if (programName != "cstitch" && programName != "stitch") { // uh oh
    QMessageBox::critical(NULL, tr("Bad project file"),
                          tr("Sorry, ") + fileString +
                          tr(" is not a valid project file ") +
                          tr("(diagnostic: wrong first line)"));
    return;
  }

  int lineCount = 0;
  const int maxLineCount = 100000;
  const QString endTag = "</" + programName + ">";
  QString thisString = "";
  do {
    thisString = textInStream.readLine();
    inString += thisString + "\n";
    ++lineCount;
    if (lineCount > maxLineCount) {
      QMessageBox::critical(NULL, tr("Bad project file"),
                            tr("Sorry, ") + fileString +
                            tr(" appears to be corrupted ") +
                            tr("(diagnostic: bad separator)"));
      return;
    }
  } while (thisString != endTag);

  QDomDocument doc;
  const bool xmlLoadSuccess = doc.setContent(inString);
  if (!xmlLoadSuccess) {
    QMessageBox::critical(NULL, tr("Bad project file"),
                          tr("Sorry, ") + fileString +
                          tr(" appears to be corrupted ") +
                          tr("(diagnostic: parse failed)"));
    return;
  }
  // a blank line between the xml and the image
  inString += textInStream.readLine() + "\n";

  // hide everything except progress meters while we regenerate this project
  hideWindows_ = true;
  hideWindows();

  // how many total images are we restoring?
  int imageCount = 1; // one colorChooser image
  imageCount += doc.elementsByTagName("color_compare_image").size();
  imageCount += doc.elementsByTagName("square_window_image").size();
  imageCount += doc.elementsByTagName("pattern_window_image").size();
  groupProgressDialog progressMeter(imageCount);
  progressMeter.setMinimumDuration(2000);
  progressMeter.setWindowModality(Qt::WindowModal);
  progressMeter.show();
  progressMeter.bumpCount();
  altMeter::setGroupMeter(&progressMeter);

  // read the image file name
  const QString fileName = ::getElementText(doc, "image_name");
  // read the project version number
  setProjectVersion(::getElementAttribute(doc, "cstitch", "version"));
  // now read the binary data image
  inFile.seek(inString.length());
  QDataStream imageStream(&inFile);
  QImage newImage;
  imageStream >> newImage;
  inFile.seek(inString.length());
  QDataStream imageData(&inFile);
  QByteArray imageByteArray;
  imageData >> imageByteArray;
  reset(newImage, imageByteArray, fileName);

  //// colorChooser
  colorChooser_.window()->setNewImage(newImage);
  progressMeter.bumpCount();

  //// colorCompare
  QDomElement colorCompareElement =
    doc.elementsByTagName("color_compare").item(0).toElement();
  if (!colorCompareElement.isNull()) {
    colorChooser* colorChooserObject = colorChooser_.window();
    QDomNodeList compareImagesList(colorCompareElement.
                                   elementsByTagName("color_compare_image"));
    for (int i = 0, size = compareImagesList.size(); i < size; ++i) {
      QDomElement thisCompareElement(compareImagesList.item(i).toElement());
      const int hiddenColorCompareIndex = colorChooserObject->
        recreateImage(colorCompareSaver(thisCompareElement));
      progressMeter.bumpCount();
      //// squareWindow
      colorCompare* colorCompareObject = colorCompareWindow_.window();
      QDomNodeList squareImagesList(thisCompareElement.
                                    elementsByTagName("square_window_image"));
      if (!squareImagesList.isEmpty()) {
        for (int ii = 0, iiSize = squareImagesList.size(); ii < iiSize; ++ii) {
          QDomElement thisSquareElement(squareImagesList.item(ii).toElement());
          const int hiddenSquareImageIndex = colorCompareObject->
            recreateImage(squareWindowSaver(thisSquareElement));
          progressMeter.bumpCount();
          squareWindow* squareWindowObject = squareWindow_.window();
          //// patternWindow
          // restore this square image's children before restoring its history
          // (the children may have their own different histories)
          QDomNodeList
            patternImageList(thisSquareElement.
                             elementsByTagName("pattern_window_image"));
          if (!patternImageList.isEmpty()) {
            for (int iii = 0, iiiSize = patternImageList.size();
                 iii < iiiSize; ++iii) {
              QDomElement thisPatternElement(patternImageList.item(iii).
                                             toElement());
              squareWindowObject->
                recreatePatternImage(patternWindowSaver(thisPatternElement));
              patternWindow_.window()->updateHistory(thisPatternElement);
              progressMeter.bumpCount();
            }
          }
          squareWindowObject->updateImageHistory(thisSquareElement);
          // if this image was only created so that one of its children could be
          // recreated, remove it (its data has already been stored away)
          if (hiddenSquareImageIndex != -1) {
            squareWindowObject->removeImage(hiddenSquareImageIndex);
          }
        }
      }
      // if this image was only created so that one of its children could be
      // recreated, remove it (its data has already been stored away)
      if (hiddenColorCompareIndex != -1) {
        colorCompareObject->removeImage(hiddenColorCompareIndex);
      }
    }
  }

  //// restore window wide settings that are independent of a particular image
  QDomElement windowGlobals(doc.elementsByTagName("global_settings").
                            item(0).toElement());
  if (colorChooserAction_->isEnabled() && colorChooser_.window()) {
    colorChooser_.window()->updateCurrentSettings(windowGlobals);
  }
  if (colorCompareAction_->isEnabled() && colorCompareWindow_.window()) {
    colorCompareWindow_.window()->updateCurrentSettings(windowGlobals);
  }
  if (squareWindowAction_->isEnabled() && squareWindow_.window()) {
    squareWindow_.window()->updateCurrentSettings(windowGlobals);
    squareWindow_.window()->checkAllColorLists();
  }
  if (patternWindowAction_->isEnabled() && patternWindow_.window()) {
    patternWindow_.window()->updateCurrentSettings(windowGlobals);
  }
  // read the image number of colors (before the reset)
  const int colorCount = ::getElementText(doc, "color_count").toInt();
  originalImageColorCount_ = colorCount;
  // call while hideWindows_ (if colorCount wasn't 0 it won't be recalculated)
  startOriginalImageColorCount();
  hideWindows_ = false;
  altMeter::setGroupMeter(NULL);
  projectFilename_ = fileString;
  setWindowTitles(QFileInfo(projectFilename_).fileName());
  setNewWidgetGeometryAndRaise(colorChooser_.window());
}