本文整理汇总了C++中QPixmap::save方法的典型用法代码示例。如果您正苦于以下问题:C++ QPixmap::save方法的具体用法?C++ QPixmap::save怎么用?C++ QPixmap::save使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QPixmap
的用法示例。
在下文中一共展示了QPixmap::save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: on_captureIntro_pushButton_clicked
void MainWindow::on_captureIntro_pushButton_clicked()
{
QString fileName;
QPixmap pixmap;
QPixmap pix;
//this->width ()
//pix = pixmap.grabWidget (this,680,130,300,540); // 獲取當前窗口 (0 , 0, -1, -1)
//获取抓取的横纵坐标
//int grapX= year_lineEdit->geometry ().x ();
//int grapY = year_lineEdit->geometry ().y ();
//使用grabWidget 获取截图 gridLayout_2
pix = pixmap.grabWidget (this->explain_textEdit, 0 ,0, this->explain_textEdit->width (), this->explain_textEdit->height () );
if (pix.isNull())
{
QMessageBox::information(this, "error", "grab Screen failed!", QMessageBox::Ok);
}
else
{
QString path = QFileDialog::getExistingDirectory(this, tr("Open Directory"),"/home",QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if(path!="")
{
fileName = path+"/说明截图.png";
if (!pix.save(fileName, "PNG"))
{
QMessageBox::information(this, "right", "保存失败!", QMessageBox::Ok);
}
else
{
QMessageBox::information(this, "Grab", "保存成功!", QMessageBox::Ok);
}
}
}
}
示例2: App
int
main (int argc, char **argv)
{
char src[MAX_PATH+1], ext[MAX_PATH+1];
QString dst;
int i, w = 0;
if (argc < 2) usage (argv[0]);
memset (src, 0, sizeof (src));
memset (ext, 0, sizeof (ext));
snprintf (src, sizeof (src) - 1, "%s", argv[1]);
i = strlen (src) - 1;
while ((i >= 0) && (src[i] != '.')) i--;
if (i<0) usage (argv[0]);
src[i] = '\0'; i++;
snprintf (ext, sizeof (ext) - 1, "%s", &(src[i]));
if (strncmp (ext, "xpm", 4) == 0) {
dst.sprintf ("new_%s.xpm", src);
} else {
dst.sprintf ("%s.xpm", src);
}
if (argc > 2) { w = atoi (argv[2]); }
QApplication App (argc, argv);
QPixmap srcpm (src, ext);
if (w) srcpm = srcpm.scaledToWidth (w, Qt::FastTransformation);
srcpm.save (dst, "xpm");
return (0);
}
示例3: savePicture
void JsExtender::savePicture()
{
if ( !QFile::exists( m_tempFile ) )
{
jsCall( "handleError", "savePicFailed" );
return;
}
QString pFile = QDesktopServices::storageLocation( QDesktopServices::PicturesLocation );
if ( m_mainWindow->eidCard() )
pFile += QString( "%1%2.jpg" ).arg( QDir::separator() ).arg( m_mainWindow->eidCard()->getId() );
QString file = QFileDialog::getSaveFileName( m_mainWindow, tr( "Save picture" ), pFile, tr( "JPEG (*.jpg *.jpeg);;PNG (*.png);;TIFF (*.tif *.tiff);;24-bit Bitmap (*.bmp)" ) );
if( file.isEmpty() )
return;
QString ext = QFileInfo( file ).suffix();
if( ext != "png" && ext != "jpg" && ext != "jpeg" && ext != "tiff" && ext != "bmp" )
file.append( ".jpg" );
QPixmap pix;
if ( !pix.load( m_tempFile + "_big.jpg" ) )
{
jsCall( "handleError", "savePicFailed" );
return;
}
pix.save( file );
}
示例4: uploadProfilePhoto
void Application::uploadProfilePhoto(const QImage &tosend, const PeerId &peerId) {
PreparedPhotoThumbs photoThumbs;
QVector<MTPPhotoSize> photoSizes;
QPixmap thumb = QPixmap::fromImage(tosend.scaled(160, 160, Qt::KeepAspectRatio, Qt::SmoothTransformation));
photoThumbs.insert('a', thumb);
photoSizes.push_back(MTP_photoSize(MTP_string("a"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0)));
QPixmap medium = QPixmap::fromImage(tosend.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation));
photoThumbs.insert('b', medium);
photoSizes.push_back(MTP_photoSize(MTP_string("b"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0)));
QPixmap full = QPixmap::fromImage(tosend);
photoThumbs.insert('c', full);
photoSizes.push_back(MTP_photoSize(MTP_string("c"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)));
QByteArray jpeg;
QBuffer jpegBuffer(&jpeg);
full.save(&jpegBuffer, "JPG", 87);
PhotoId id = MTP::nonce<PhotoId>();
MTPPhoto photo(MTP_photo(MTP_long(id), MTP_long(0), MTP_int(MTP::authedId()), MTP_int(unixtime()), MTP_string(""), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes)));
QString file, filename;
int32 filesize = 0;
QByteArray data;
ReadyLocalMedia ready(ToPreparePhoto, file, filename, filesize, data, id, id, peerId, photo, photoThumbs, MTP_documentEmpty(MTP_long(0)), jpeg, false);
connect(App::uploader(), SIGNAL(photoReady(MsgId, const MTPInputFile &)), App::app(), SLOT(photoUpdated(MsgId, const MTPInputFile &)), Qt::UniqueConnection);
MsgId newId = clientMsgId();
App::app()->regPhotoUpdate(peerId, newId);
App::uploader()->uploadMedia(newId, ready);
}
示例5: writeDecoration
void QTableModelWordMLWriter::writeDecoration(QXmlStreamWriter & stream, const QVariant & decoration)
{
QIcon icon = qvariant_cast<QIcon>(decoration);
QPixmap pixmap;
if (icon.isNull()){
pixmap = qvariant_cast<QPixmap>(decoration);
if (pixmap.isNull()){
return;
}
} else {
pixmap = icon.pixmap(16, 16);
}
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
pixmap.save(&buffer, "PNG"); // writes pixmap into bytes in PNG format
stream.writeStartElement("w:pict");
// export image data
stream.writeStartElement("w:binData");
stream.writeAttribute("w:name", QString("wordml://%1.png").arg(m_imageId, 8, 10, QLatin1Char('0')));
stream.writeAttribute("xml:space", "preserve");
stream.writeCharacters(bytes.toBase64());
stream.writeEndElement();
//
stream.writeStartElement("v:shape");
stream.writeAttribute("style", QString("width:%1px;height:%2px").arg(pixmap.size().width()).arg(pixmap.size().height()));
stream.writeEmptyElement("v:imageData");
stream.writeAttribute("src", QString("wordml://%1.png").arg(m_imageId, 8, 10, QLatin1Char('0')));
// end tag <w:shape>
stream.writeEndElement();
// end tag <w:pict>
stream.writeEndElement();
m_imageId++;
}
示例6: savePlot
/**
* This method allows the user to save the plot as a png,
* jpg, or tif image file.
*/
void ScatterPlotWindow::savePlot() {
QPixmap pixmap;
QString output =
QFileDialog::getSaveFileName((QWidget *)parent(),
"Choose output file",
"./",
QString("Images (*.png *.jpg *.tif)"));
if (output.isEmpty()) return;
//Make sure the filename is valid
if (!output.isEmpty()) {
if(!output.endsWith(".png") && !output.endsWith(".jpg") && !output.endsWith(".tif")) {
output = output + ".png";
}
}
QString format = QFileInfo(output).suffix();
pixmap = QPixmap::grabWidget(p_plot);
std::string formatString = format.toStdString();
if (!pixmap.save(output,formatString.c_str())) {
QMessageBox::information((QWidget *)parent(),"Error","Unable to save "+ output);
return;
}
}
示例7:
void GuiBehind::sendScreenStage2() {
// Screenshot
QPixmap screen = QPixmap::grabWindow(QApplication::desktop()->winId());
// Restore window
mView->setWindowState(Qt::WindowActive);
// Salvataggio screenshot in file
QTemporaryFile tempFile;
tempFile.setAutoRemove(false);
tempFile.open();
mScreenTempPath = tempFile.fileName();
tempFile.close();
screen.save(mScreenTempPath, "JPG", 95);
// Prepare file transfer
QString ip;
qint16 port;
if (!prepareStartTransfer(&ip, &port)) return;
// Start screen transfer
mDuktoProtocol.sendScreen(ip, port, mScreenTempPath);
}
示例8: addIconFromRes
void IconManager::addIconFromRes(int catId, const QString &iconName, const QString & resName)
{
// QIcon _icon(resName);
QPixmap pix = QIcon(resName).pixmap(48, 48);
int lastPos = resName.lastIndexOf("/");
QString fileName = resName.mid(lastPos + 1);
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
//bytes << icon;
//buffer << (buffer, icon);
pix.save(&buffer, "PNG");
QString sql = "INSERT INTO Icons (catId, name, fileName, iconData) VALUES (?, ?, ?, ?)";
QSqlQuery *q = new QSqlQuery(db);
q->prepare(sql);
q->addBindValue(catId);
q->addBindValue(iconName);
q->addBindValue(fileName);
q->addBindValue(bytes);
q->exec();
delete q;
}
示例9: NavigateHome
void CustomWebView::NavigateHome ()
{
QFile file (":/resources/html/home.html");
file.open (QIODevice::ReadOnly);
QString data = file.readAll ();
data.replace ("{pagetitle}",
tr ("Welcome to LeechCraft!"));
data.replace ("{title}",
tr ("Welcome to LeechCraft!"));
data.replace ("{body}",
tr ("Welcome to LeechCraft, the integrated internet-client.<br />"
"More info is available on the <a href='http://leechcraft.org'>"
"project's site</a>."));
QBuffer iconBuffer;
iconBuffer.open (QIODevice::ReadWrite);
QPixmap pixmap (":/resources/images/poshuku.svg");
pixmap.save (&iconBuffer, "PNG");
data.replace ("{img}",
QByteArray ("data:image/png;base64,") + iconBuffer.buffer ().toBase64 ());
setHtml (data);
}
示例10: thumbnailCreated
void SpeedDial::thumbnailCreated(const QPixmap &image)
{
PageThumbnailer* thumbnailer = qobject_cast<PageThumbnailer*>(sender());
if (!thumbnailer) {
return;
}
QString url = thumbnailer->url().toString();
QString fileName = m_thumbnailsDir + QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md4).toHex() + ".png";
if (image.isNull()) {
fileName = "qrc:/html/broken-page.png";
}
else {
if (!image.save(fileName)) {
qWarning() << "SpeedDial::thumbnailCreated Cannot save thumbnail to " << fileName;
}
fileName = QUrl::fromLocalFile(fileName).toString();
}
m_regenerateScript = true;
for (int i = 0; i < m_webFrames.count(); i++) {
QWebFrame* frame = m_webFrames.at(i).data();
if (!frame) {
m_webFrames.removeAt(i);
i--;
continue;
}
frame->evaluateJavaScript(QString("setImageToUrl('%1', '%2');").arg(url, fileName));
}
thumbnailer->deleteLater();
}
示例11: reportTorCheckResults
//.........这里部分代码省略.........
headline = tr("Tor is Working Properly. You Can Browse Anonymously.");
bulletone = tr("You can confirm this yourself by visiting <a href='https://check.torproject.org'>https://check.torproject.org</a>");
bullettwo = tr("The bookmark toolbar contains some well known hidden services you can check out.");
bulletthree = tr("You can check Tor at any time by pressing F12 or clicking <b>Tools->Check Tor.</b>");
img = QLatin1String(":graphics/tor-on.png");
statusbar = QLatin1String("Tor Check Successful");
break;
default:
setBrowsingEnabled(false);
/* Stop the periodic tor checks until we're back up */
m_timer->stop();
title = tr("Check Your Tor Installation");
if (!m_torIsRunning) {
headline = tr("Tor Is Not Running On Your Computer!");
bulletone = tr("Check that you have installed Tor.");
bullettwo = tr("Check that you have started Tor.");
} else if (page == NOT_USING_TOR) {
headline = tr("Torora May Be By-Passing Tor!");
bulletone = tr("Testing at https://check.torproject.org indicated that you are not using Tor.");
bullettwo = tr("Your set-up seems OK, Tor is running and seem to be correctly configured.");
bulletfour = tr("<li>Click 'Change Identity' in Vidalia or TorK and try again. The exit node used for the test may not be listed with the checking service yet.</li>");
} else {
headline = tr("The Tor Check Website May Be Down!");
bulletone = tr("Check that https://check.torproject.org is available using another browser.");
bullettwo = tr("There may be a temporary issue with the website.");
bulletfour = tr("<li>Click 'Change Identity' in Vidalia or TorK and try again. The exit node used for the test may not be listed with the checking service yet.</li>");
}
bulletthree = tr("Press F12 or <b>Tools->Check Tor</b> to test Tor again.");
img = QLatin1String(":graphics/tor-off.png");
statusbar = QLatin1String("Tor Check Failed");
tororaIssues = QString(QLatin1String("<table align='center'><tr><td></td> <td>"
"<object type=\"application/x-qt-plugin\" classid=\"QPushButton\" "
"name=\"TryAgainButton\" height=25 width=110></object>\n"
"<script>\n"
"document.TryAgainButton.text = 'Try Again';\n"
"</script>\n"
"</td> <td></td></tr></table>\n"));
/* Create a new circuit for the next test, just in case we used an exit that isn't listed yet */
if (torcontrol)
torcontrol->newIdentity();
setBrowsingEnabled(false);
break;
}
QString html = QString(QLatin1String(file.readAll()))
.arg(title)
.arg(QString())
.arg(headline)
.arg(bulletone)
.arg(bullettwo)
.arg(bulletthree)
.arg(bulletfour)
.arg(tororaIssues);
QBuffer imageBuffer;
imageBuffer.open(QBuffer::ReadWrite);
QIcon icon = QIcon(img);
QPixmap pixmap = icon.pixmap(QSize(32, 32));
if (pixmap.save(&imageBuffer, "PNG")) {
html.replace(QLatin1String("IMAGE_BINARY_DATA_HERE"),
QString(QLatin1String(imageBuffer.buffer().toBase64())));
}
if (page == USING_TOR) {
imageBuffer.open(QBuffer::ReadWrite);
icon = QIcon(QLatin1String(":graphics/info.png"));
pixmap = icon.pixmap(QSize(32, 32));
if (pixmap.save(&imageBuffer, "PNG")) {
html.replace(QLatin1String("INFO_IMAGE_HERE"),
QString(QLatin1String(imageBuffer.buffer().toBase64())));
}
imageBuffer.open(QBuffer::ReadWrite);
icon = QIcon(QLatin1String(":graphics/important.png"));
pixmap = icon.pixmap(QSize(32, 32));
if (pixmap.save(&imageBuffer, "PNG")) {
html.replace(QLatin1String("WARNING_IMAGE_HERE"),
QString(QLatin1String(imageBuffer.buffer().toBase64())));
}
imageBuffer.open(QBuffer::ReadWrite);
icon = QIcon(QLatin1String(":graphics/help.png"));
pixmap = icon.pixmap(QSize(32, 32));
if (pixmap.save(&imageBuffer, "PNG")) {
html.replace(QLatin1String("QUESTION_IMAGE_HERE"),
QString(QLatin1String(imageBuffer.buffer().toBase64())));
}
}
BrowserApplication::instance()->mainWindow()->currentTab()->page()->mainFrame()->setHtml(html, QUrl());
if (!m_checkTorSilently && page == USING_TOR)
connectToTor();
if (!m_checkTorSilently) {
m_statusbar=statusbar;
QTimer::singleShot(1000, this, SLOT(displayStatusResult()));
if (page != TOR_CHECK)
BrowserApplication::instance()->mainWindow()->setStatusBarMessagesEnabled(true);
}
}
示例12: generatePageFromQStringList
//.........这里部分代码省略.........
{
generalHTMLPart->write ( QString ( "<div class=\"statgroup\">" ) );
generalHTMLPart->write ( i18np ( "<b>Average message length:</b> %1 character<br>",
"<b>Average message length:</b> %1 characters<br>", m_contact->messageLength() ) );
generalHTMLPart->write ( i18np ( "<b>Time between two messages:</b> %1 second",
"<b>Time between two messages:</b> %1 seconds", m_contact->timeBetweenTwoMessages() ) );
generalHTMLPart->write ( QString ( "</div>" ) );
generalHTMLPart->write ( QString ( "<div class=\"statgroup\">" ) );
generalHTMLPart->write ( i18n ( "<b title=\"The last time you talked with %1\">Last talk :</b> %2<br>", m_contact->metaContact()->displayName(), KGlobal::locale()->formatDateTime ( m_contact->lastTalk() ) ) );
generalHTMLPart->write ( i18n ( "<b title=\"The last time %1 was online or away\">Last time present :</b> %2", m_contact->metaContact()->displayName(), KGlobal::locale()->formatDateTime ( m_contact->lastPresent() ) ) );
generalHTMLPart->write ( QString ( "</div>" ) );
//generalHTMLPart->write(QString("<div class=\"statgroup\">"));
//generalHTMLPart->write(i18n("<b title=\"%1 uses to set his status online at these hours (EXPERIMENTAL)\">Main online events :</b><br>").arg(m_contact->metaContact()->displayName()));
//QValueList<QTime> mainEvents = m_contact->mainEvents(Kopete::OnlineStatus::Online);
//for (uint i=0; i<mainEvents.count(); i++)
//generalHTMLPart->write(QString("%1<br>").arg(mainEvents[i].toString()));
//generalHTMLPart->write(QString("</div>"));
generalHTMLPart->write ( "<div title=\"" +i18n ( "Current status" ) + "\" class=\"statgroup\">" );
generalHTMLPart->write ( i18n ( "Is <b>%1</b> since <b>%2</b>",
Kopete::OnlineStatus ( m_contact->oldStatus() ).description(),
KGlobal::locale()->formatDateTime ( m_contact->oldStatusDateTime() ) ) );
generalHTMLPart->write ( QString ( "</div>" ) );
}
/*
* Chart which shows the hours where plugin has seen this contact online
*/
generalHTMLPart->write ( QString ( "<div class=\"statgroup\">" ) );
generalHTMLPart->write ( QString ( "<table width=\"100%\"><tr><td colspan=\"3\">" )
+ i18nc ( "TRANSLATOR: please reverse 'left' and 'right' as appropriate for your language",
"When was this contact visible?<br />All charts are in 24 blocks, "
"one per hour, encompassing one day. %1 is on the left, "
"and %2 is on the right.", KGlobal::locale()->formatTime ( QTime ( 0, 0 ) ),
KGlobal::locale()->formatTime ( QTime ( 23, 59 ) ) )
+ QString ( "</td></tr>" ) );
generalHTMLPart->write ( QString ( "<tr><td height=\"200\" valign=\"bottom\" colspan=\"3\" class=\"chart\">" ) );
QString chartString;
QByteArray colorPath;
QPixmap pixmap ( 1, 1 );
pixmap.fill ( Qt::black );
// Generate base64 picture.
QByteArray tempArray;
QBuffer tempBuffer ( &tempArray );
tempBuffer.open ( QIODevice::WriteOnly );
if ( pixmap.save ( &tempBuffer, "PNG" ) )
colorPath = tempArray.toBase64();
for ( uint i=0; i<24; i++ )
{
int hrWidth = qRound ( ( double ) ( hoursOnline[i] + hoursAway[i] ) / ( double ) hours[iMaxHours]*100. );
chartString += QString ( "<img class=\"margin:0px;\" height=\"" )
+ ( totalTime ? QString::number ( hrWidth ) : QString::number ( 0 ) )
+ QString ( "\" src=\"data:image/png;base64," )
+colorPath
+"\" width=\"4%\" title=\""
+i18n ( "Between %1 and %2, %3 was visible for %4% of the hour.",
KGlobal::locale()->formatTime ( QTime ( i, 0 ) ),
KGlobal::locale()->formatTime ( QTime ( ( i+1 ) % 24, 0 ) ),
m_contact->metaContact()->displayName(), hrWidth )
+ QString ( "\">" );
}
generalHTMLPart->write ( chartString );
generalHTMLPart->write ( QString ( "</td></tr>" ) );
generalHTMLPart->write ( QString ( "<tr><td>" )
+i18n ( "Online time" )
+QString ( "</td><td>" )
+i18n ( "Away time" )
+QString ( "</td><td>" )
+i18n ( "Offline time" )
+QString ( "</td></tr><td valign=\"bottom\" width=\"33%\" class=\"chart\">" ) );
generalHTMLPart->write ( generateHTMLChart ( hoursOnline, hoursAway, hoursOffline, i18n ( "online" ),
m_onlineColor ) );
generalHTMLPart->write ( QString ( "</td><td valign=\"bottom\" width=\"33%\" class=\"chart\">" ) );
generalHTMLPart->write ( generateHTMLChart ( hoursAway, hoursOnline, hoursOffline, i18n ( "away" ),
m_awayColor ) );
generalHTMLPart->write ( QString ( "</td><td valign=\"bottom\" width=\"33%\" class=\"chart\">" ) );
generalHTMLPart->write ( generateHTMLChart ( hoursOffline, hoursAway, hoursOnline, i18n ( "offline" ),
m_offlineColor ) );
generalHTMLPart->write ( QString ( "</td></tr></table></div>" ) );
if ( subTitle == i18n ( "General information" ) )
/* On main page, show the different status of the contact today
*/
{
generalHTMLPart->write ( QString ( todayString ) );
}
generalHTMLPart->write ( QString ( "</body></html>" ) );
generalHTMLPart->end();
}
示例13: QDialog
showAnCalChrRes::showAnCalChrRes(customRect *rect, QImage* origEditImg, QWidget *parent) :
QDialog(parent),
ui(new Ui::showAnCalChrRes)
{
ui->setupUi(this);
//internOrigEditImg = origEditImg;
//Get rectangle
//..
globalRect = rect;
qreal rx1,ry1,rx2,ry2;
//rect->rect().getRect(&rx1,&ry1,&rw,&rh);
rect->rect().getCoords(&rx1,&ry1,&rx2,&ry2);
globalCalStruct.x1 = (int)rx1;
globalCalStruct.y1 = (int)ry1;
globalCalStruct.x2 = (int)rx2;
globalCalStruct.y2 = (int)ry2;
globalCalStruct.canvasW = rect->parameters.W;
globalCalStruct.canvasH = rect->parameters.H;
//Prepare variables
//..
int w, h, W, H;
//QPixmap tmpPix(_PATH_DISPLAY_IMAGE);
QPixmap tmpPix = QPixmap::fromImage(*origEditImg);
W = tmpPix.width();
H = tmpPix.height();
w = rect->parameters.canvas->width();
h = rect->parameters.canvas->height();
//qDebug() << "Canvas w: " << w;
//qDebug() << "Canvas h: " << h;
//qDebug() << "x1: " << globalCalStruct.x1;
//qDebug() << "y1: " << globalCalStruct.y1;
//qDebug() << "x2: " << globalCalStruct.x2;
//qDebug() << "y2: " << globalCalStruct.y2;
//Extrapolate dimensions
globalCalStruct.X1 = round( ((float)W/(float)w)*(float)globalCalStruct.x1 );
globalCalStruct.Y1 = round( ((float)H/(float)h)*(float)globalCalStruct.y1 );
globalCalStruct.X2 = round( ((float)W/(float)w)*(float)globalCalStruct.x2 );
globalCalStruct.Y2 = round( ((float)H/(float)h)*(float)globalCalStruct.y2 );
globalCalStruct.lenW = abs(globalCalStruct.X2-globalCalStruct.X1);
globalCalStruct.lenH = abs(globalCalStruct.Y2-globalCalStruct.Y1);
globalCalStruct.origImgW = W;
globalCalStruct.origImgH = H;
//qDebug() << "p1: " << globalCalStruct.x1 << ", " << globalCalStruct.y1;
//qDebug() << "p2: " << globalCalStruct.x2 << ", " << globalCalStruct.y2;
//qDebug() << "P1: " << globalCalStruct.X1 << ", " << globalCalStruct.Y1;
//qDebug() << "P2: " << globalCalStruct.X2 << ", " << globalCalStruct.Y2;
//qDebug() << "lenW: " << globalCalStruct.lenW;
//qDebug() << "lenH: " << globalCalStruct.lenH;
//Crop & show image
//..
//qDeleteAll(canvasSpec->scene()->items());
int tmpOffset = 10;
QPixmap cropped = tmpPix.copy( QRect( globalCalStruct.X1, globalCalStruct.Y1, globalCalStruct.lenW, globalCalStruct.lenH ) );
cropped.save("./tmpImages/tmpCropped.ppm");
QGraphicsScene *scene = new QGraphicsScene(0,0,cropped.width(),cropped.height());
ui->canvasCroped->setBackgroundBrush(cropped);
ui->canvasCroped->setCacheMode(QGraphicsView::CacheNone);
ui->canvasCroped->setScene( scene );
ui->canvasCroped->resize(cropped.width(),cropped.height());
float toolBarW = ui->frame->width();
int newW = (cropped.width()>toolBarW)?cropped.width():toolBarW;
this->resize(QSize(newW+(tmpOffset*2),cropped.height()+(tmpOffset*2)+ui->frame->height()));
int framex = round((float)(this->width()-ui->frame->width())/2.0);
int framey = ui->canvasCroped->height()+tmpOffset;
ui->frame->move(QPoint(framex,framey));
int canvasx = round((float)(this->width()-ui->canvasCroped->width())/2.0);
ui->canvasCroped->move(QPoint(canvasx,0));
ui->canvasCroped->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
ui->canvasCroped->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );
//Update lines
//..
globalRedLine = new customLine(QPoint(0,0),QPoint(0,0),QPen(Qt::red));
globalGreenLine = new customLine(QPoint(0,0),QPoint(0,0),QPen(Qt::green));
globalBlueLine = new customLine(QPoint(0,0),QPoint(0,0),QPen(Qt::blue));
drawSensitivities();
}
示例14: prepareImages
void LocalImageLoaderPrivate::prepareImages() {
QString file, filename, mime, stickerMime = qsl("image/webp");
int32 filesize = 0;
QImage img;
QByteArray data;
PeerId peer;
uint64 id, thumbId = 0;
int32 duration = 0;
QString thumbExt = "jpg";
ToPrepareMediaType type;
bool animated = false;
bool ctrlShiftEnter = false;
MsgId replyTo = 0;
{
QMutexLocker lock(loader->toPrepareMutex());
ToPrepareMedias &list(loader->toPrepareMedias());
if (list.isEmpty()) return;
file = list.front().file;
img = list.front().img;
data = list.front().data;
peer = list.front().peer;
id = list.front().id;
type = list.front().type;
duration = list.front().duration;
ctrlShiftEnter = list.front().ctrlShiftEnter;
replyTo = list.front().replyTo;
}
if (img.isNull()) {
if (!file.isEmpty()) {
QFileInfo info(file);
if (type == ToPrepareAuto) {
QString lower(file.toLower());
const QStringList &photoExtensions(cPhotoExtensions());
for (QStringList::const_iterator i = photoExtensions.cbegin(), e = photoExtensions.cend(); i != e; ++i) {
if (lower.lastIndexOf(*i) == lower.size() - i->size()) {
if (info.size() < MaxUploadPhotoSize) {
type = ToPreparePhoto;
break;
}
}
}
if (type == ToPrepareAuto && info.size() < MaxUploadDocumentSize) {
type = ToPrepareDocument;
}
}
if (type == ToPrepareDocument) {
mime = mimeTypeForFile(info).name();
}
if (type != ToPrepareAuto && info.size() < MaxUploadPhotoSize) {
bool opaque = (mime != stickerMime);
img = App::readImage(file, 0, opaque, &animated);
}
filename = info.fileName();
filesize = info.size();
} else if (!data.isEmpty()) {
if (type != ToPrepareAudio) {
img = App::readImage(data, 0, true, &animated);
if (type == ToPrepareAuto) {
if (!img.isNull() && data.size() < MaxUploadPhotoSize) {
type = ToPreparePhoto;
} else if (data.size() < MaxUploadDocumentSize) {
type = ToPrepareDocument;
} else {
img = QImage();
}
}
}
MimeType mimeType = mimeTypeForData(data);
if (type == ToPrepareDocument || type == ToPrepareAudio) {
mime = mimeType.name();
}
if (mime == "image/jpeg") {
filename = filedialogDefaultName(qsl("image"), qsl(".jpg"), QString(), true);
} else if (type == ToPrepareAudio) {
filename = filedialogDefaultName(qsl("audio"), qsl(".ogg"), QString(), true);
mime = "audio/ogg";
} else {
QString ext;
QStringList patterns = mimeType.globPatterns();
if (!patterns.isEmpty()) {
ext = patterns.front().replace('*', QString());
}
filename = filedialogDefaultName((type == ToPrepareAudio) ? qsl("audio") : qsl("doc"), ext, QString(), true);
}
filesize = data.size();
}
} else {
if (type == ToPrepareDocument) {
filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true);
mime = mimeTypeForName("image/png").name();
data = QByteArray();
{
QBuffer b(&data);
img.save(&b, "PNG");
}
filesize = data.size();
} else {
if (img.hasAlphaChannel()) {
//.........这里部分代码省略.........
示例15: exportToPNG
void ModelExportHelper::exportToPNG(ObjectsScene *scene, const QString &filename, float zoom, bool show_grid, bool show_delim)
{
if(!scene)
throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__);
try
{
QPixmap pix;
QRectF ret=scene->itemsBoundingRect();
bool shw_grd, shw_dlm, align_objs;
QGraphicsView viewp(scene);
QRect retv;
QPolygon pol;
//Clear the object scene selection to avoid drawing the selectoin rectangle of the objects
scene->clearSelection();
//Make a backup of the current scene options
ObjectsScene::getGridOptions(shw_grd, align_objs, shw_dlm);
//Sets the options passed by the user
ObjectsScene::setGridOptions(show_grid, false, show_delim);
//Updates the scene to apply the change on grid and delimiter
scene->update();
//Configures the viewport alignment to top-left coordinates.
viewp.setAlignment(Qt::AlignLeft | Qt::AlignTop);
//Apply the zoom factor on the viewport
viewp.resetTransform();
viewp.centerOn(0,0);
viewp.scale(zoom, zoom);
//Convert the objects bounding rect to viewport coordinates to correctly draw them onto pixmap
pol=viewp.mapFromScene(ret);
//Configure the viewport area to be copied
retv.setTopLeft(pol.at(0));
retv.setTopRight(pol.at(1));
retv.setBottomRight(pol.at(2));
retv.setBottomLeft(pol.at(3));
//Creates the output pixmap
pix=QPixmap(retv.size());
pix.fill();
QPainter p(&pix);
//Setting optimizations on the painter
p.setRenderHint(QPainter::Antialiasing, true);
p.setRenderHint(QPainter::TextAntialiasing, true);
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
emit s_progressUpdated(50, trUtf8("Rendering objects onto the output pixmap..."), BASE_OBJECT);
//Render the entire viewport onto the pixmap
viewp.render(&p, QRectF(QPointF(0,0), pix.size()), retv);
//Restore the scene options
ObjectsScene::setGridOptions(shw_grd, align_objs, shw_dlm);
//Updates the scene to apply the restoration of grid and delimiter statuses
scene->update();
//If the pixmap is not saved raises an error
if(!pix.save(filename))
throw Exception(Exception::getErrorMessage(ERR_FILE_NOT_WRITTEN).arg(Utf8String::create(filename)),
ERR_FILE_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__);
emit s_exportFinished();
}
catch(Exception &e)
{
throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
}
}