// [[Rcpp::export]] Rcpp::RawVector magick_image_write( XPtrImage input, Rcpp::CharacterVector format, Rcpp::IntegerVector quality, Rcpp::IntegerVector depth, Rcpp::CharacterVector density, Rcpp::CharacterVector comment){ if(!input->size()) return Rcpp::RawVector(0); XPtrImage image = copy(input); #if MagickLibVersion >= 0x691 //suppress write warnings see #74 and #116 image->front().quiet(true); #endif if(format.size()) for_each ( image->begin(), image->end(), Magick::magickImage(std::string(format[0]))); if(quality.size()) for_each ( image->begin(), image->end(), Magick::qualityImage(quality[0])); if(depth.size()) for_each ( image->begin(), image->end(), Magick::depthImage(depth[0])); if(density.size()){ for_each ( image->begin(), image->end(), Magick::resolutionUnitsImage(Magick::PixelsPerInchResolution)); for_each ( image->begin(), image->end(), Magick::densityImage(Point(density[0]))); } if(comment.size()) for_each ( image->begin(), image->end(), Magick::commentImage(std::string(comment.at(0)))); Magick::Blob output; writeImages( image->begin(), image->end(), &output ); Rcpp::RawVector res(output.length()); std::memcpy(res.begin(), output.data(), output.length()); return res; }
// [[Rcpp::export]] Rcpp::IntegerVector magick_image_write_integer(XPtrImage input){ if(input->size() != 1) throw std::runtime_error("Image must have single frame to write a native raster"); Frame frame = input->front(); Magick::Geometry size(frame.size()); size_t width = size.width(); size_t height = size.height(); Magick::Blob output; frame.write(&output, "RGBA", 8L); Rcpp::IntegerVector res(output.length() / 4); memcpy(res.begin(), output.data(), output.length()); res.attr("class") = Rcpp::CharacterVector::create("nativeRaster"); res.attr("dim") = Rcpp::NumericVector::create(height, width); return res; }
//---------------------------------------------------------------------------------------------------------------------- // Image Magick Image loading routines //---------------------------------------------------------------------------------------------------------------------- bool Image::load( const std::string &_fname ) noexcept { #ifdef IMAGE_DEBUG_ON std::cerr<<"loading with ImageMagick"<<std::endl; #endif Magick::Image image; Magick::Blob blob; try { image.read(_fname); // need to flip image as OpenGL uses textures starting the other way round. image.flip(); image.write(&blob, "RGBA"); } catch (Magick::Error& Error) { std::cout << "Error loading texture '" << _fname << "': " << Error.what() << std::endl; return false; } m_width=image.columns(); m_height=image.rows(); m_channels=4; m_format=GL_RGBA; m_data.reset(new unsigned char[ m_width*m_height*m_channels]); // simple memcpy of the blob data to our internal data, not worrying about RGB/RGBA // here (as OpenGL doesn't really either). memcpy(m_data.get(),blob.data(),blob.length()); return true; }
char osra_cuneiform_ocr(Magick::Image &cuneiform_img, const string &char_filter) { Magick::Blob blob; cuneiform_img.write(&blob, "DIB"); size_t data_size = blob.length(); char *dib = new char[data_size]; memcpy(dib, blob.data(), data_size); char str[256]; memset(str, 0, sizeof(str)); if (!PUMA_XOpen(dib, NULL) || !PUMA_XFinalRecognition() || !PUMA_SaveToMemory(NULL, PUMA_TOTEXT, PUMA_CODE_ASCII, str, sizeof(str) - 1)) { //if (verbose) // cout << "Cuneiform recognition failed." << endl; PUMA_XClose(); delete []dib; return UNKNOWN_CHAR; } PUMA_XClose(); delete []dib; // As we have initialized the image with two identical samples, it is expected that they go in the string // one after another, or separated by space (e.g. "ZZ\n" or "Z Z\n"). if (((str[0] == str[1] && isspace(str[2])) || (str[0] == str[2] && str[1] == ' ')) && isalnum(str[0]) && (char_filter.empty() || char_filter.find(str[0], 0) != string::npos)) return str[0]; return UNKNOWN_CHAR; }
void Targets::plotTarget (rts2db::Target *tar, XmlRpc::HttpParams *params, const char* &response_type, char* &response, size_t &response_length) { response_type = "image/jpeg"; AltPlot ap (params->getInteger ("w", 800), params->getInteger ("h", 600)); Magick::Geometry size (params->getInteger ("w", 800), params->getInteger ("h", 600)); double from = params->getDouble ("from", 0); double to = params->getDouble ("to", 0); if (from < 0 && to == 0) { // just fr specified - from to = time (NULL); from += to; } else if (from == 0 && to == 0) { // default - one day to = time (NULL); from = to - 86400; } Magick::Image mimage (size, "white"); ap.getPlot (from, to, tar, &mimage); Magick::Blob blob; mimage.write (&blob, "jpeg"); response_length = blob.length(); response = new char[response_length]; memcpy (response, blob.data(), response_length); }
void Night::printAlt (int year, int month, int day, XmlRpc::HttpParams *params, const char* &response_type, char* &response, size_t &response_length) { response_type = "image/jpeg"; AltPlot ap (params->getInteger ("w", 800), params->getInteger ("h", 600)); Magick::Geometry size (params->getInteger ("w", 800), params->getInteger ("h", 600)); time_t from; int64_t duration; getNightDuration (year, month, day, from, duration); time_t end = from + duration; rts2db::ImageSetDate is = rts2db::ImageSetDate (from, end); is.load (); Magick::Image mimage (size, "white"); ap.getPlot (from, end, &is, &mimage); Magick::Blob blob; mimage.write (&blob, "jpeg"); response_length = blob.length(); response = new char[response_length]; memcpy (response, blob.data(), response_length); }
void PipelineStabDetect::onInput(InputImageInfo info, Magick::Image image) { try { if (!initialized) { init(image); } if (image.rows() != height || image.columns() != width) { throw runtime_error(QString("Not uniform image size! %").arg(info.file.fileName()).toStdString()); } Magick::Blob blob; // set raw RGBS output format & convert it into a Blob if (image.depth() > 8) *err << "Warning: we lost some information by converting to 8bit depth (now " << image.depth() << ")" << endl; image.depth(8); image.magick("RGB"); image.write(&blob); LocalMotions localmotions; VSFrame frame; size_t dataLen = blob.length(); Q_ASSERT(fi.planes == 1); Q_ASSERT(dataLen == image.baseColumns() * image.baseRows() * 3); if (stabConf->mdConf.show > 0) { // create copy of blob frame.data[0] = new uint8_t[dataLen]; memcpy(frame.data[0], blob.data(), dataLen); } else { frame.data[0] = (uint8_t*) blob.data(); } frame.linesize[0] = image.baseColumns() * 3; if (vsMotionDetection(&md, &localmotions, &frame) != VS_OK) { throw runtime_error("motion detection failed"); } else { if (vsWriteToFile(&md, f, &localmotions) != VS_OK) { throw runtime_error("cannot write to transform file"); } vs_vector_del(&localmotions); } if (stabConf->mdConf.show > 0) { // if we want to store transformations, we have to create new image... Magick::Geometry g(width, height); Magick::Blob oblob(frame.data[0], dataLen); Magick::Image oimage; oimage.read(oblob, g, 8, "RGB"); delete[] frame.data[0]; emit input(info, oimage); } else { emit input(info, image); } } catch (exception &e) { emit error(e.what()); } }
std::unique_ptr<Image> loadImageFromFile(const std::string& fname) { try { Magick::Image image(config().imagesPath + fname); Magick::Blob blob; image.write(&blob, "RGBA"); std::vector<uint8_t> data(blob.length()); memcpy(&data.front(), blob.data(), blob.length()); std::cout << "Loaded image " << fname << std::endl; return std::unique_ptr<Image>(new Image(std::move(data), Size(image.size().width(), image.size().height()))); } catch (const Magick::Exception& ex) { std::cerr << "Error while trying to load image: " << fname << ", reason: " << ex.what() << std::endl; return defaultImage(); } }
// [[Rcpp::export]] Rcpp::RawVector magick_image_write_frame(XPtrImage input, const char * format, size_t i = 1){ if(input->size() < 1) throw std::runtime_error("Image must have at least 1 frame to write a bitmap"); Frame frame = input->at(i-1); //zero indexing! Magick::Geometry size(frame.size()); size_t width = size.width(); size_t height = size.height(); Magick::Blob output; frame.write(&output, format, 8L); if(output.length() == 0) throw std::runtime_error("Unsupported raw format: " + std::string(format)); if(output.length() % (width * height)) throw std::runtime_error("Dimensions do not add up, '" + std::string(format) + "' may not be a raw format"); size_t slices = output.length() / (width * height); Rcpp::RawVector res(output.length()); memcpy(res.begin(), output.data(), output.length()); res.attr("class") = Rcpp::CharacterVector::create("bitmap", format); res.attr("dim") = Rcpp::NumericVector::create(slices, width, height); return res; }
void FsImgStorage::Write(ImgInfo& img) const { Utils::Contract::Assert(img.GetId() != IMGID_UNDEFINED); Utils::Contract::Assert(!img.GetFileExtension().empty()); boost::filesystem::path uploadFilePath = GetImgPath(img.GetId(), img.GetFileExtension()); Magick::Blob magickBlob; img.GetMagickImage().write(&magickBlob); Utils::FileSystem::WriteAllBytes((const char*)magickBlob.data(), magickBlob.length(), uploadFilePath); }
void Targets::processForm (XmlRpc::HttpParams *params, const char* &response_type, char* &response, size_t &response_length) { #ifdef RTS2_HAVE_LIBJPEG if (!strcmp (params->getString ("plot", "xxx"), "Plot target altitude")) { response_type = "image/jpeg"; AltPlot ap (params->getInteger ("w", 800), params->getInteger ("h", 600)); Magick::Geometry size (params->getInteger ("w", 800), params->getInteger ("h", 600)); double from = params->getDouble ("from", 0); double to = params->getDouble ("to", 0); if (from < 0 && to == 0) { // just fr specified - from to = time (NULL); from += to; } else if (from == 0 && to == 0) { // default - one hour to = time (NULL); from = to - 86400; } std::list < int > ti; for (XmlRpc::HttpParams::iterator iter = params->begin (); iter != params->end (); iter++) { if (!strcmp (iter->getName (), "tid")) ti.push_back (atoi (iter->getValue ())); } rts2db::TargetSet ts = rts2db::TargetSet (); ts.load (ti); Magick::Image mimage (size, "white"); ap.getPlot (from, to, &ts, &mimage); Magick::Blob blob; mimage.write (&blob, "jpeg"); response_length = blob.length(); response = new char[response_length]; memcpy (response, blob.data(), response_length); return; } #endif // RTS2_HAVE_LIBJPEG }
void CMagicKHelper::GetPhotoBinval( const tstring& strPhotoName, tstring& strBinval ) { try { CLogger::GetInstance()->PrintErrLog("begin getphotoBinval"); Magick::Image imgSrc(strPhotoName); CLogger::GetInstance()->PrintErrLog("imgSrc()"); Magick::Blob blob; // EnterCriticalSection(cs_); imgSrc.write(&blob); // LeaveCriticalSection(cs_); CLogger::GetInstance()->PrintErrLog("write()"); unsigned int len = blob.length(); strBinval.assign((const char*)blob.data(), blob.length()); CLogger::GetInstance()->PrintErrLog("write()"); } catch (std::exception &ex) { CLogger::GetInstance()->PrintErrLog("resize image failure %s", ex.what()); } }
ItemSequence_t FormatFunction::evaluate( const ExternalFunction::Arguments_t& aArgs, const StaticContext* aSctxCtx, const DynamicContext* aDynCtx) const { Magick::Image lImage; ImageFunction::getOneImageArg(aDynCtx, aArgs, 0, lImage); Magick::Blob lBlob; lImage.write(&lBlob); long lBlobLength = (long) lBlob.length(); std::string lImageType = GetImageType(lBlob.data(), &lBlobLength); String lResult(lImageType); return ItemSequence_t(new SingletonItemSequence( theModule->getItemFactory()->createString(lResult))); }
ResizeTest(std::string fileName) { source.loadFile(fileName); for (int i=1; i<99; ++i) { Magick::Image image = source.getImage(); image.magick("JPEG"); image.quality(50); Magick::Geometry resizeGeometry; resizeGeometry.percent(true); resizeGeometry.width(i); resizeGeometry.height(i); image.resize(resizeGeometry); Magick::Blob blob; image.write(&blob); imghash::Source target((char*)blob.data(), blob.length()); images.push_back(target); } }
void photoalbum::api::map::map_tile_km( const jsonrpc::request& request, jsonrpc::result& result, sqlite::connection& conn ) { const std::string region = request.params().get<std::string>(0); const int eastings = request.params().get<int>(1); const int northings = request.params().get<int>(2); photoalbum::map::tile_data_db data_db; db::get( conn, region, eastings/10, northings/10, data_db ); try { Magick::Image image(Magick::Blob( reinterpret_cast<const void*>(&(data_db.data[0])), data_db.data.size() ) ); Magick::Geometry out_size( image.size().width()/5, image.size().height()/5 ); Magick::Image out_image(out_size, Magick::Color(255,255,255)); int off_x = -(out_size.width() * (eastings%5)); int off_y = -(out_size.height() * (4 - (northings%5))); out_image.composite(image, off_x, off_y); Magick::Blob blob; out_image.write(&blob, "PNG"); png_data(result.data()).data() = base64::encode( reinterpret_cast<const unsigned char*>(blob.data()), blob.length() ); } catch(const std::exception& e) { } }
void ImageItem::rotate(short degrees) { if (!degrees) return; QString file = absoluteFilePath(); Magick::Image image; image.read(file.toStdString()); image.rotate(degrees); image.write(file.toStdString()); Magick::Blob buffer; image.write(&buffer); QImage thumbnail; thumbnail.loadFromData((const uchar*) buffer.data(), buffer.length()); thumbnail.save(absoluteThumbPath(), "JPEG"); }
Glib::RefPtr<Gdk::Pixbuf> createCoverPixBufWithOverlay(const AlbumArt& albumArt, int32_t size) { try { std::stringstream finalGeometry; finalGeometry << size << "x" << size; std::stringstream intermediateGeometry; intermediateGeometry << overlayWidth << "x" << overlayHeight << "!"; std::stringstream albumArtGeometry; albumArtGeometry << coverWidth << "x" << coverHeight << "!"; Magick::Blob coverImageBlob(&(albumArt.getData().front()), albumArt.getData().size()); Magick::Image coverImage(coverImageBlob); coverImage.scale(Magick::Geometry(albumArtGeometry.str())); Magick::Blob cdCaseBlob(cdCaseData, sizeof(cdCaseData)); Magick::Image cdCase(cdCaseBlob, Magick::Geometry(intermediateGeometry.str()), "PNG"); Magick::Quantum maxRgb; {using namespace Magick; maxRgb = MaxRGB;} // Magick::MaxRGB; quits with the compile-time error "'Quantum' was not declared in this scope" Magick::Image result(Magick::Geometry(intermediateGeometry.str()), Magick::Color(0, 0, 0, maxRgb)); result.composite(coverImage, coverImageOffsetX, coverImageOffsetY, Magick::CopyCompositeOp); result.composite(cdCase, 0, 0, Magick::OverCompositeOp); result.scale(Magick::Geometry(finalGeometry.str())); Magick::Blob data; result.write(&data, "PNG"); Glib::RefPtr<Gdk::PixbufLoader> loader = Gdk::PixbufLoader::create(); loader->set_size(size, size); loader->write((guint8*)data.data(), data.length()); Glib::RefPtr<Gdk::Pixbuf> pixBuf = loader->get_pixbuf(); loader->close(); return pixBuf; } catch (Magick::Exception& e) { log::warn("Creating cover with overlay failed: %s", e.what()); return createCoverPixBuf(albumArt, size); } }
QImage ImageFactoryThumbnail::image() { // try loading cached thumbnail of exported image Magick::Image thumbnail = m_config->db()->cache().retrieve(m_config->config(),true); if( !thumbnail.isValid() ) { // fallback to loading cached thumbnail embedded in RAW image thumbnail = m_config->db()->cache().retrieve(m_config->raw(),true); if( !thumbnail.isValid() ) { qDebug() << "ImageFactoryThumbnail::image() invalid" << m_config->raw(); return QImage(); } } Magick::Blob blob; thumbnail.write( &blob ); qDebug() << "ImageFactoryThumbnail::image()" << thumbnail.size().width() << "x" << thumbnail.size().height(); return QImage::fromData( QByteArray( static_cast<const char*>(blob.data()), blob.length() ) ); }
ItemSequence_t ExifFunction::evaluate( const ExternalFunction::Arguments_t& aArgs, const StaticContext* aSctxCtx, const DynamicContext* aDynCtx) const { Magick::Image lImage; ImageFunction::getOneImageArg(aDynCtx, aArgs, 0, lImage); String lTag = ImageFunction::getOneStringArg(aArgs, 1); std::string lTagWithExif("EXIF:"); lTagWithExif += lTag.c_str(); Magick::Blob lBlob; lImage.write(&lBlob); long lBlobLength = (long) lBlob.length(); std::string lExifValue = GetExifValue(lBlob.data(), &lBlobLength, lTagWithExif); if (lExifValue == "") { return ItemSequence_t(new EmptySequence()); } return ItemSequence_t(new SingletonItemSequence( theModule->getItemFactory()->createString(String(lExifValue)))); }
void Night::printAltAz (int year, int month, int day, XmlRpc::HttpParams *params, const char* &response_type, char* &response, size_t &response_length) { response_type = "image/jpeg"; time_t from; int64_t duration; getNightDuration (year, month, day, from, duration); time_t end = from + duration; rts2db::ImageSetDate is = rts2db::ImageSetDate (from, end); is.load (); int s = params->getInteger ("s", 250); AltAz altaz = AltAz (s, s); altaz.plotAltAzGrid (); for (rts2db::ImageSetDate::iterator iter = is.begin (); iter != is.end (); iter++) { struct ln_hrz_posn hrz; try { (*iter)->getCoordBestAltAz (hrz, rts2core::Configuration::instance ()->getObserver ()); (*iter)->closeFile (); altaz.plotCross (&hrz, NULL, "green"); } catch (rts2core::Error &er) { (*iter)->closeFile (); } } Magick::Blob blob; altaz.write (&blob, "jpeg"); response_length = blob.length(); response = new char[response_length]; memcpy (response, blob.data(), response_length); }
void AltAzTarget::authorizedExecute (XmlRpc::XmlRpcSource *source, std::string path, XmlRpc::HttpParams *params, const char* &response_type, char* &response, size_t &response_length) { // get new AltAz graph rts2json::AltAz altaz = rts2json::AltAz (); // plot its AltAz grid altaz.plotAltAzGrid (); struct ln_hrz_posn hrz; // retrieve from database set of all targets.. rts2db::TargetSet ts = rts2db::TargetSet (); ts.load (); // iterate through the set, plot location of each target for (rts2db::TargetSet::iterator iter = ts.begin (); iter != ts.end (); iter++) { // retrieve target AltAz coordinates (*iter).second->getAltAz (&hrz); // and plot them with proper caption if (hrz.alt > -2) altaz.plotCross (&hrz, (*iter).second->getTargetName ()); } // write image to blob as JPEG Magick::Blob blob; altaz.write (&blob, "JPEG"); // set MIME response type response_type = "image/jpeg"; // lenght of response response_length = blob.length(); // create and fill response buffer response = new char[response_length]; memcpy (response, blob.data(), response_length); }
QByteArray ApplicationHelper::getCaptcha(const QString& text, const int width, const int height) { qsrand(QTime::currentTime().msec()); Magick::InitializeMagick(NULL); Magick::Image image( QString("%1x%2").arg(width).arg(height).toStdString().c_str(), "white" ); image.addNoise(Magick::GaussianNoise); image.fontPointsize(25); image.strokeColor("black"); image.floodFillColor(Magick::Geometry(0, 0, 1, 1), Magick::ColorRGB(qrand() % 200, qrand() % 150, qrand() % 10 + 200)); const QList<int> v{10, 10,10, 5,10, height - 20,10, height - 5,width - 10, 10,width - 10, 20,width - 10, height - 10,width - 10, height - 30}; double * controlPoints = new double[v.size()]; std::copy(v.begin(), v.end(), controlPoints); image.distort(Magick::PerspectiveDistortion, v.size(), controlPoints); image.annotate("\n" + text.toStdString(), Magick::Geometry(150, 110), Magick::NorthGravity); image.blur(1, 5); image.addNoise(Magick::GaussianNoise); image.opacity(0.3); //image.randomThreshold(Magick::Geometry(4,4)); Magick::Blob blob; image.write(&blob, "PNG"); delete[] controlPoints; return QByteArray((char *) blob.data(), blob.length()); }
QImage ImageItem::previewRotate(short degrees) { Magick::Image image; if (m_tempImage) { m_tempImage->open(); image.read(m_tempImage->fileName().toStdString()); image.magick("jpg"); } else { image.read(absoluteFilePath().toStdString()); m_tempImage = new QTemporaryFile(qApp); m_tempImage->open(); } image.rotate(degrees); Magick::Blob buffer; image.write(&buffer); QImage output; output.loadFromData((const uchar*) buffer.data(), buffer.length()); output.save(m_tempImage, "JPEG"); m_tempImage->close(); return output; }
void PipelineStabTransform::onInput(InputImageInfo info, Magick::Image image) { try { if (!initialized) { init(image); } if (image.rows() != height || image.columns() != width) { throw runtime_error(QString("Not uniform image size! %").arg(info.file.fileName()).toStdString()); } Q_ASSERT(image.baseColumns() == width && image.baseRows() == height); Magick::Blob blob; // set raw RGBS output format & convert it into a Blob if (image.depth() > 8) *err << "Warning: we lost some information by converting to 8bit depth (now " << image.depth() << ")" << endl; image.depth(8); image.magick("RGB"); image.write(&blob); Q_ASSERT(blob.length() == image.baseColumns() * image.baseRows() * 3); // inframe VSFrame inframe; size_t dataLen = blob.length(); inframe.data[0] = (uint8_t*) blob.data(); inframe.linesize[0] = image.baseColumns() * 3; // TODO: it is correct? // outframe uint8_t* data = new uint8_t[dataLen]; //memcpy(data, blob.data(), dataLen); VSFrame outframe; outframe.data[0] = data; outframe.linesize[0] = image.baseColumns() * 3; // TODO: it is correct? if (vsTransformPrepare(&td, &inframe, &outframe) != VS_OK) { throw runtime_error("Failed to prepare transform"); } Q_ASSERT(vsTransformGetSrcFrameInfo(&td)->planes == 1); vsDoTransform(&td, vsGetNextTransform(&td, &trans)); vsTransformFinish(&td); Magick::Geometry g(width, height); Magick::Blob oblob(data, dataLen); Magick::Image oimage; oimage.size(g); oimage.depth(8); oimage.magick("RGB"); oimage.read(oblob); delete[] data; info.luminance = -1; emit input(info, oimage); } catch (exception &e) { emit error(e.what()); } }
void TimeLapseCapture::imageCaptured(QString format, Magick::Blob blob, Magick::Geometry sizeHint) { bool readRawFromFile = false; QString framePath = output.path() + QDir::separator() + leadingZeros(capturedCnt, FRAME_FILE_LEADING_ZEROS) + "_" + leadingZeros(capturedSubsequence, 2); if (format == "RGB") { if (storeRawImages) { // store RAW RGB data in PPM format QString pgmHeader = QString("P6\n%1 %2\n255\n").arg(sizeHint.width()).arg(sizeHint.height()); std::string headerStr = pgmHeader.toStdString(); const char *headerBytes = headerStr.c_str(); size_t headerLen = strlen(headerBytes); if (shutterSpdAlg != NULL && capturedSubsequence == 0) { Magick::Image capturedImage; capturedImage.read(blob, sizeHint, 8, "RGB"); shutterSpdAlg->update(capturedImage); } framePath += ".ppm"; QFile file(framePath); file.open(QIODevice::WriteOnly); file.write(headerBytes, headerLen); file.write((char*) blob.data(), blob.length()); file.close(); } else { // convert RGB data to JPEG Magick::Image capturedImage; capturedImage.read(blob, sizeHint, 8, "RGB"); if (shutterSpdAlg != NULL && capturedSubsequence == 0) { shutterSpdAlg->update(capturedImage); } QDateTime now = QDateTime::currentDateTime(); QString exifDateTime = now.toString("yyyy:MM:dd HH:mm:ss");\ // ImageMagick don't support writing of exif data // TODO: setup exif timestamp correctly capturedImage.attribute("EXIF:DateTime", exifDateTime.toStdString()); //capturedImage.defineValue("EXIF", "DateTime", exifDateTime.toStdString()); capturedImage.compressType(Magick::JPEGCompression); capturedImage.magick("JPEG"); framePath += ".jpeg"; capturedImage.write(framePath.toStdString()); } } else { if (shutterSpdAlg != NULL && capturedSubsequence == 0) { try { Magick::Image capturedImage; capturedImage.read(blob, format.toStdString()); shutterSpdAlg->update(capturedImage); } catch (const std::exception &e) { err << "Failed to decode captured image (" << format << "): " << QString::fromUtf8(e.what()) << endl; readRawFromFile = true; } } // store other formats in device specific format framePath += "." + format; QFile file(framePath); file.open(QIODevice::WriteOnly); file.write((char*) blob.data(), blob.length()); file.close(); if (readRawFromFile && shutterSpdAlg != NULL && capturedSubsequence == 0) { /* I don't understand ImageMagick correctly, but it fails with reading RAW files * from memory blob, but reading from file works (sometimes). * Maybe, it don't support delegating (dcraw, ufraw...) with memory data... */ try { Magick::Image capturedImage; capturedImage.read(framePath.toStdString()); shutterSpdAlg->update(capturedImage); } catch (const std::exception &e) { err << "Failed to decode captured image (" << framePath << "): " << QString::fromUtf8(e.what()) << endl; } } } verboseOutput << "Captured frame saved to " << framePath << endl; capturedSubsequence++; }
// // Output filter. // static apr_status_t resize_output_filter(ap_filter_t* f, apr_bucket_brigade* in_bb) { request_rec* rec =f->r; resize_conf* conf = (resize_conf*)ap_get_module_config(rec->per_dir_config, &resizeimage_module); const char* content_type, *target_type = "JPEG"; const char* image_url, *resize_param, *image_hash=NULL; Magick::Blob blob; char* vlob = NULL; size_t vlob_length = 0; int cache_hit = FALSE; AP_LOG_VERBOSE(rec, "Incoming %s.", __FUNCTION__); // Pass thru by request types. if(rec->status!=HTTP_OK || rec->main!=NULL || rec->header_only || (rec->handler!= NULL && strcmp(rec->handler, "default-handler") == 0)) goto PASS_THRU; AP_LOG_VERBOSE(rec, "-- Checking responce headers."); // Obtain and erase x-resize-image header or pass through. image_url = get_and_unset_header(rec->headers_out, X_RESIZE); if(image_url== NULL || image_url[0]=='\0') { image_url = get_and_unset_header(rec->err_headers_out, X_RESIZE); } if(image_url==NULL || image_url[0]=='\0') goto PASS_THRU; // Check content-type content_type = rec->content_type; if(content_type) { if(strcasecmp(content_type, "image/jpeg")==0) { target_type = "JPEG"; } else if(strcasecmp(content_type, "image/png")==0) { target_type = "PNG"; } else if(strcasecmp(content_type, "image/gif")==0) { target_type = "GIF"; } else goto PASS_THRU; } // Resize parameter resize_param = get_and_unset_header(rec->headers_out, X_RESIZE_PARAM); if(resize_param==NULL || resize_param[0]=='\0') { resize_param = get_and_unset_header(rec->err_headers_out, X_RESIZE_PARAM); } if(resize_param[0]=='\0') resize_param = NULL; // Image hash image_hash = get_and_unset_header(rec->headers_out, X_RESIZE_HASH); if(image_hash==NULL || image_hash[0]=='\0') { image_hash = get_and_unset_header(rec->err_headers_out, X_RESIZE_HASH); } // Open image and resize. AP_LOG_INFO(rec, "URL: %s, %s => %s (%s)", image_url, content_type, resize_param, image_hash); if(image_hash) { // Try memcached... image_hash = apr_psprintf(rec->pool, "%s:%s:%s", image_hash, target_type, resize_param); memcached_return r; uint32_t flags; vlob = memcached_get(conf->memc, image_hash, strlen(image_hash), &vlob_length, &flags, &r); if(r==MEMCACHED_SUCCESS) { AP_LOG_DEBUG(rec, "Restored from memcached: %s, len=%d", image_hash, vlob_length); cache_hit = TRUE; goto WRITE_DATA; } else { AP_LOG_DEBUG(rec, "Can't restore from memcached: %s - %s(%d)", image_hash, memcached_strerror(conf->memc, r), r); } } // Reszize try { Magick::Image image; image.read(image_url); if(resize_param) image.zoom(resize_param); image.magick(target_type); image.quality(conf->jpeg_quality); image.write(&blob); vlob = (char*)blob.data(); vlob_length = blob.length(); } catch(Magick::Exception& err) { AP_LOG_ERR(rec, __FILE__ ": Magick failed: %s", err.what()); goto PASS_THRU; } if(image_hash) { // Store to memcached... memcached_return r = memcached_set(conf->memc, image_hash, strlen(image_hash), vlob, vlob_length, conf->expire, 0); if(r==MEMCACHED_SUCCESS) { AP_LOG_DEBUG(rec, "Stored to memcached: %s(len=%d)", image_hash, vlob_length); } else { AP_LOG_DEBUG(rec, "Can't store from memcached: %s(len=%d) - %s(%d)", image_hash, vlob_length,memcached_strerror(conf->memc, r), r); } } WRITE_DATA: AP_LOG_VERBOSE(rec, "-- Creating resize buckets."); // Drop all content and headers related. while(!APR_BRIGADE_EMPTY(in_bb)) { apr_bucket* b = APR_BRIGADE_FIRST(in_bb); apr_bucket_delete(b); } rec->eos_sent = 0; rec->clength = 0; unset_header(rec, "Content-Length"); unset_header(rec, "Content-Encoding"); unset_header(rec, "Last-Modified"); unset_header(rec, "ETag"); // Start resize bucket. { apr_off_t remain = vlob_length, offset = 0; while(remain>0) { apr_off_t bs = (remain<AP_MAX_SENDFILE)? remain: AP_MAX_SENDFILE; char* heap = (char*)malloc(bs); memcpy(heap, vlob+offset, bs); apr_bucket* b = apr_bucket_heap_create(heap, bs, free, in_bb-> bucket_alloc); APR_BRIGADE_INSERT_TAIL(in_bb, b); remain -= bs; offset += bs; } APR_BRIGADE_INSERT_TAIL(in_bb, apr_bucket_eos_create(in_bb->bucket_alloc)); ap_set_content_length(rec, vlob_length); if(cache_hit) free(vlob); } AP_LOG_VERBOSE(rec, "-- Create done."); PASS_THRU: AP_LOG_VERBOSE(rec, "-- Filter done."); ap_remove_output_filter(f); return ap_pass_brigade(f->next, in_bb); }
void CurrentPosition::authorizedExecute (XmlRpc::XmlRpcSource *source, std::string path, XmlRpc::HttpParams *params, const char* &response_type, char* &response, size_t &response_length) { int s = params->getInteger ("s", 250); rts2json::AltAz altaz = rts2json::AltAz (s, s); altaz.rotation = params->getInteger ("rot", 180); altaz.mirror = params->getBoolean ("mirror", true); bool showHorizon = params->getBoolean ("horizon", true); bool showSunMoon = params->getBoolean ("sunmoon", true); double bsc_limmag = params->getDouble ("starsmag", 3.9); double bsc_maxsize = params->getDouble ("starssize", 0); if (!bsc_maxsize && s >= 250) bsc_maxsize = 2.5; struct ln_equ_posn pos; struct ln_hrz_posn hrz; double JD = ln_get_julian_from_sys (); if (bsc_maxsize > 0.0) { for (bsc_record *star = bsc; star->hrn >= 0; star++) { if (star->mag > bsc_limmag) continue; pos.ra = star->ra; pos.dec = star->dec; ln_get_hrz_from_equ (&pos, Configuration::instance ()->getObserver (), JD, &hrz); if (hrz.alt <= 0.0) continue; altaz.plot (&hrz, NULL, "grey30", PLOT_TYPE_POINT, - (star->mag - bsc_limmag) / bsc_limmag * bsc_maxsize); } } if (showHorizon) altaz.plotAltAzHorizon (); altaz.plotAltAzGrid (); // position of sun & moon if (showSunMoon) { ln_get_solar_equ_coords (JD, &pos); ln_get_hrz_from_equ (&pos, Configuration::instance ()->getObserver (), JD, &hrz); altaz.plot (&hrz, "☉", "OrangeRed", PLOT_TYPE_POINT, 4); ln_get_lunar_equ_coords (JD, &pos); ln_get_hrz_from_equ (&pos, Configuration::instance ()->getObserver (), JD, &hrz); altaz.plot (&hrz, "☾", "grey10", PLOT_TYPE_POINT, 4); } // get current target position.. HttpD *serv = (HttpD *) getMasterApp (); rts2core::Connection *conn = serv->getOpenConnection (DEVICE_TYPE_MOUNT); rts2core::Value *val; if (conn) { val = conn->getValue ("TEL_"); if (val && val->getValueType () == RTS2_VALUE_ALTAZ) { hrz.alt = ((rts2core::ValueAltAz *) val)->getAlt (); hrz.az = ((rts2core::ValueAltAz *) val)->getAz (); altaz.plot (&hrz, "TEL", "red", PLOT_TYPE_TELESCOPE, 12); } val = conn->getValue ("TAR"); if (val && val->getValueType () == RTS2_VALUE_RADEC) { pos.ra = ((rts2core::ValueRaDec *) val)->getRa (); pos.dec = ((rts2core::ValueRaDec *) val)->getDec (); if (!(std::isnan (pos.ra) || std::isnan (pos.dec))) { ln_get_hrz_from_equ (&pos, Configuration::instance ()->getObserver (), JD, &hrz); altaz.plotCross (&hrz, NULL, "blue"); } } } #ifdef RTS2_HAVE_PGSQL conn = serv->getOpenConnection (DEVICE_TYPE_EXECUTOR); if (conn) { rts2db::Target *tar; val = conn->getValue ("current"); if (val && val->getValueInteger () >= 0) { tar = createTarget (val->getValueInteger (), Configuration::instance ()->getObserver (), Configuration::instance ()->getObservatoryAltitude ()); if (tar) { tar->getAltAz (&hrz, JD); altaz.plotCross (&hrz, tar->getTargetName (), "green"); delete tar; } } val = conn->getValue ("next"); if (val && val->getValueInteger () >= 0) { tar = createTarget (val->getValueInteger (), Configuration::instance ()->getObserver (), Configuration::instance ()->getObservatoryAltitude ()); if (tar) { tar->getAltAz (&hrz, JD); altaz.plotCross (&hrz, tar->getTargetName (), "blue"); delete tar; } } } #endif /* RTS2_HAVE_PGSQL */ Magick::Blob blob; altaz.write (&blob, "JPEG"); response_type = "image/jpeg"; response_length = blob.length(); response = new char[response_length]; memcpy (response, blob.data(), response_length); }
void Graph::plotValue (rts2db::Recval *rv, double from, double to, XmlRpc::HttpParams *params, const char* &response_type, char* &response, size_t &response_length) { ValuePlot vp (rv->getId (), rv->getType ()); const char *type = params->getString ("t", "A"); rts2json::PlotType pt; switch (*type) { case 'l': pt = rts2json::PLOTTYPE_LINE; break; case 'L': pt = rts2json::PLOTTYPE_LINE_SHARP; break; case 'c': pt = rts2json::PLOTTYPE_CROSS; break; case 'C': pt = rts2json::PLOTTYPE_CIRCLES; break; case 's': pt = rts2json::PLOTTYPE_SQUARES; break; case 'f': pt = rts2json::PLOTTYPE_FILL; break; case 'F': pt = rts2json::PLOTTYPE_FILL_SHARP; break; case 'A': default: pt = rts2json::PLOTTYPE_AUTO; } Magick::Geometry size (params->getInteger ("w", 800), params->getInteger ("h", 600)); from = params->getDate ("from", from); to = params->getDate ("to", to, true); if (from < 0 && to == 0) { // just fr specified - from to = time (NULL); from += to; } else if (from == 0 && to == 0) { // default - one hour to = time (NULL); from = to - 86400; } Magick::Image mimage (size, "white"); vp.getPlot (from, to, &mimage, pt, params->getInteger ("lw", 3), params->getInteger ("sh", 3), params->getBoolean ("pn", true), params->getBoolean ("ps", true), params->getBoolean ("l", true)); Magick::Blob blob; mimage.write (&blob, "JPEG"); response_length = blob.length(); response = new char[response_length]; memcpy (response, blob.data(), response_length); }
ImagePtr MagickImageLoader::makeImage(Magick::Blob& blob) { uchar * new_data = new uchar[blob.length()]; memcpy(new_data, blob.data(), blob.length()); return ImagePtr(new Image(new_data, blob.length(), Image::AllocatorNew)); }
std::string get_blob_data(const Magick::Blob& blob) { const char* data = static_cast<const char*>(blob.data()); size_t length = blob.length(); return std::string(data,data+length); }