×
Namespaces

Variants
Actions
(Difference between revisions)

Capturing image using QML Camera and uploading to Facebook

From Nokia Developer Wiki
Jump to: navigation, search
kunal_the_one (Talk | contribs)
(Kunal the one -)
hamishwillee (Talk | contribs)
m (Text replace - "<code cpp>" to "<code cpp-qt>")
 
(16 intermediate revisions by 5 users not shown)
Line 1: Line 1:
[[Category:Qt Mobility]][[Category:Qt Quick]][[Category:Qt WebKit]][[Category:Networking]][[Category:Symbian]][[Category:MeeGo]][[Category:Code Snippet]]
+
[[Category:Qt Mobility]][[Category:Qt Quick]][[Category:Qt WebKit]][[Category:Symbian]][[Category:MeeGo Harmattan]][[Category:Code Examples]][[Category:Camera]][[Category:Web Services]][[Category:Symbian^3]]
{{Abstract|This article explains how to ... }} '
+
{{Abstract|This article demonstrates how to capture an image using the QML Camera Element and share it to Facebook. }}  
  
 
{{ArticleMetaData <!-- v1.2 -->
 
{{ArticleMetaData <!-- v1.2 -->
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
+
|sourcecode= [[Media:FacebookHelper.zip]]  
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
|devices= <!-- Devices tested against - e.g. ''devices=Nokia 6131 NFC, Nokia C7-00'') -->
+
|devices= Nokia N9
|sdk= <!-- Qt SDK 1.2 (e.g. [http://linktosdkdownload/ Qt SDK 1.2]) -->
+
|sdk= Qt SDK 1.2  
|platform= <!-- Symbian,Meego - e.g. Symbian^1 and later, Qt 4.6 and later -->
+
|platform= All Qt 4.6 and later
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
|signing=<!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|capabilities= <!-- NetworkServices  (e.g. Location, NetworkServices. -->
+
|signing= <!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
 +
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 
|keywords= <!-- QNetworkAccessManager,QML Camera -->
 
|keywords= <!-- QNetworkAccessManager,QML Camera -->
|translated-from-title= <!-- Title only -->  
+
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 +
|translated-by= <!-- [[User:XXXX]] -->
 +
|translated-from-title= <!-- Title only -->
 
|translated-from-id= <!-- Id of translated revision -->
 
|translated-from-id= <!-- Id of translated revision -->
|review-by=<!-- After re-review: [[User:username]] -->
+
|review-by= <!-- After re-review: [[User:username]] -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 
|update-timestamp= <!-- After significant update: YYYYMMDD -->
|creationdate= <!-- Format YYYYMMDD -->
+
|creationdate= 20120428
|author= [[User:kunal_the_one]]  
+
|author= [[User:Kunal the one]]
 
}}
 
}}
  
 
# How to use QML Camera element to capture Image
 
# How to login to facebook using QNetworkAccessManager
 
# How to use HTTP Post method to upload capture image to facebook album
 
''
 
 
{{Note|This is an entry in the [[PureView Imaging Competition 2012Q2]]}}
 
{{Note|This is an entry in the [[PureView Imaging Competition 2012Q2]]}}
  
 
== Introduction ==
 
== Introduction ==
  
This article explain how to use QML Camera element to capture image and then how to upload and share captured image to Facebook, using Qt Network Module.
+
This article explains how to use QML Camera element to capture an image and then how to upload and share captured image to Facebook. In more detail, it shows how to:
 +
# Use [http://doc.qt.nokia.com/qtmobility-1.2/qml-camera.html QML Camera] element to capture an image
 +
# Login to facebook using {{Qapiname|QNetworkAccessManager}}
 +
# Use HTTP Post method to upload capture image to facebook album
 +
 
 +
Following are snaps from my sample application running on N9.
 +
<gallery widths="350px" heights="200">
 +
File:fbhelper_main.png| Take picture
 +
File:fbhelper_preview.png | Picture
 +
File:fbhelper_login.png | Facebook login
 +
File:fbhelper_success.png| Picture uploaded
 +
</gallery>
  
'''Let's start with How to capture image using QML Camera.'''
+
== Using the QML Camera Element ==
  
QML Camera is part of Qt Mobility API, so you need to configure Qt's Project file to to include Qt Mobility package. We also need to use Network,Webkit and Declarative Module. For symbian we also need to specify capability to be able to connect to network, saving file, accessing camera.
+
QML Camera is part of Qt Mobility API, so you need to configure Qt's Project file to to include Qt Mobility package. We also need to use Network, Webkit and Declarative Module. For Symbian we also need to specify capabilities to be able to connect to network and access the camera.
<code cpp>
+
<code cpp-qt>
 
QT += network webkit declarative
 
QT += network webkit declarative
  
Line 51: Line 60:
 
</code>
 
</code>
  
Now our project file is ready, We can continue with QML code. Following is QML code for main.qml which I launch from main.cpp file. In Following code I am using QML Camera to display camera view and capture image with it. Once image is captured I am hiding Camera element and showing preview view.  
+
Below is QML code for '''main.qml''' which I launch from '''main.cpp''' file. The codes uses QML Camera to display camera view and capture image with it. Once image is captured the Camera element is hidden and the preview view is displayed.  
  
PreviewImage view shows captured image and it offer option to share it on Facebook. To avoid QML component dependency I have create a simple custom Button  element and using it.
+
{{Icode|PreviewImage}} view shows captured image and it offers the option to share it on Facebook. To avoid QML component dependency I have create a simple custom button element that will work on all Qt platforms.
  
<code cpp>
+
<code javascript>
 
import QtQuick 1.1
 
import QtQuick 1.1
 
import QtMultimediaKit 1.1
 
import QtMultimediaKit 1.1
Line 111: Line 120:
 
Following is PreviewImage.qml file. PreviewImage view is enabled when Image is captured, it show captured image and by pressing share button it upload the captured image on Facebook account.
 
Following is PreviewImage.qml file. PreviewImage view is enabled when Image is captured, it show captured image and by pressing share button it upload the captured image on Facebook account.
  
<code cpp>
+
<code cpp-qt>
 
import QtQuick 1.1
 
import QtQuick 1.1
 
import QtMultimediaKit 1.1
 
import QtMultimediaKit 1.1
Line 157: Line 166:
 
</code>
 
</code>
  
Now that, image is captured, We need code that allow user to login to his facebook account and upload pohto.
+
The image is now captured. The following code allows the user to login to their Facebook account and upload a photo.
  
I have create a post some time back, how to login to facebook and how to post comment on wall. [http://kunalmaemo.blogspot.com/2012/01/posting-on-facebook-wall-from-qt.html Here is link] I will use same code here to login to facebook account using QNetworkAccessManager.
+
== Facebook helper - log in to facebook and upload photos ==
 +
I created a blog [http://kunalmaemo.blogspot.com/2012/01/posting-on-facebook-wall-from-qt.html here] some time ago, explaining how to login to facebook and how to post comment on wall. I will use same code here to login to facebook account using {{Icode|QNetworkAccessManager}}.
  
First of all to login on facebook account and posting on wall or uploading photo, we need to create a application on faceook. [https://developers.facebook.com/apps Here] is link where you can create a app.
+
First of all to login on facebook account and posting on wall or uploading photo, we need to request an application ID from Facebook [https://developers.facebook.com/apps here]. With this id you can request an authorisation token from the Facebook API when you login, and use it to upload photos.
You will get applicaiton id, using which you request authorization token from facebook, which can be used to upload photo on facebook. Following is code to get authorization token from facebook.
+
  
Login method will launch facebook login webpage in QWebView, Once user enteres a valid username and password, it will redirects to https://www.facebook.com/connect/login_success.html url with access token mentioned in query string.
+
Login method will launch facebook login webpage in {{Qapiname|QWebView}}. Once a user enters a valid username and password, it will redirects to https://www.facebook.com/connect/login_success.html url with access token mentioned in query string.
  
<code cpp>
+
<code cpp-qt>
 
void FacebookHelper::login( const QString& scope ){
 
void FacebookHelper::login( const QString& scope ){
 
 
     QUrl url("https://www.facebook.com/dialog/oauth");
 
     QUrl url("https://www.facebook.com/dialog/oauth");
 
     url.addQueryItem("client_id",YOUR_APPP_ID);
 
     url.addQueryItem("client_id",YOUR_APPP_ID);
Line 196: Line 204:
 
</code>
 
</code>
  
Now we have access token, we are ready to upload photo to facebook. Following code describe the process. uploadPicture method takes absolute path to picture to upload and comment for photo, then it creates form-data request and send that to facebook using HTTP Post method.
+
Now we have access token, we are ready to upload photo to facebook. Following code describe the process. uploadPicture method takes absolute path to picture to upload and comment for photo, then it creates form-data request and send that to facebook using HTTP Post method.
  
<code cpp>
+
<code cpp-qt>
 
void FacebookHelper::uploadPicture(const QString& picLocation, const QString& comment) {
 
void FacebookHelper::uploadPicture(const QString& picLocation, const QString& comment) {
  
Line 235: Line 243:
  
 
Once we received finished signal for this request, Photo should appear on user's account.
 
Once we received finished signal for this request, Photo should appear on user's account.
 +
== Downloads ==
 +
The project source is here: [[Media:FacebookHelper.zip]]. In order to test this you will need to remember to put your Facebook app id, in '''main.cpp''' file.
 +
 
== Summary ==
 
== Summary ==
  
By using QML Camera and QNetowkAccessManager we can easily capture and share image to facebook network.
+
By using QML Camera and {{Icode|QNetwokAccessManager}} we can easily capture and share image to facebook network.
 +
 
 
Hope you enjoy the article.
 
Hope you enjoy the article.

Latest revision as of 04:20, 11 October 2012

This article demonstrates how to capture an image using the QML Camera Element and share it to Facebook.

Article Metadata
Code ExampleTested with
SDK: Qt SDK 1.2
Devices(s): Nokia N9
Compatibility
Platform(s): All Qt 4.6 and later
Symbian
Symbian^3
Article
Created: kunal_the_one (28 Apr 2012)
Last edited: hamishwillee (11 Oct 2012)

Note.pngNote: This is an entry in the PureView Imaging Competition 2012Q2

Contents

[edit] Introduction

This article explains how to use QML Camera element to capture an image and then how to upload and share captured image to Facebook. In more detail, it shows how to:

  1. Use QML Camera element to capture an image
  2. Login to facebook using QNetworkAccessManager
  3. Use HTTP Post method to upload capture image to facebook album

Following are snaps from my sample application running on N9.

[edit] Using the QML Camera Element

QML Camera is part of Qt Mobility API, so you need to configure Qt's Project file to to include Qt Mobility package. We also need to use Network, Webkit and Declarative Module. For Symbian we also need to specify capabilities to be able to connect to network and access the camera.

QT += network webkit declarative
 
CONFIG += mobility
MOBILITY = multimedia
 
symbian {
TARGET.CAPABILITY += NetworkServices \
ReadUserData \
WriteUserData \
LocalServices \
UserEnvironment
}

Below is QML code for main.qml which I launch from main.cpp file. The codes uses QML Camera to display camera view and capture image with it. Once image is captured the Camera element is hidden and the preview view is displayed.

PreviewImage view shows captured image and it offers the option to share it on Facebook. To avoid QML component dependency I have create a simple custom button element that will work on all Qt platforms.

import QtQuick 1.1
import QtMultimediaKit 1.1
 
Rectangle {
width:640;height:360
Camera {
id:camera
width:parent.width;height:parent.height
focus : visible // to receive focus and capture key events when visible
opacity: 1
 
flashMode: Camera.FlashRedEyeReduction
whiteBalanceMode: Camera.WhiteBalanceFlash
exposureCompensation: -1.0
 
onImageCaptured : {
console.debug("Captured Image:" +preview);
preview.opacity=1;
camera.opacity=0;
preview.source = preview;
}
onImageSaved: {
console.log("Image saved:"+path);
preview.opacity=1;
camera.opacity=0;
}
 
MyButton{
id:captureBtn
anchors.verticalCenter: parent.verticalCenter
anchors.right:parent.right
text:"Capture"
 
onClicked: {
camera.captureImage();
}
}
}
 
PreviewImage{
id:preview
width:parent.width;height:parent.height
opacity: 0
camera:camera
 
onHide: {
preview.opacity=0;
camera.opacity=1;
}
}
}

Following is PreviewImage.qml file. PreviewImage view is enabled when Image is captured, it show captured image and by pressing share button it upload the captured image on Facebook account.

import QtQuick 1.1
import QtMultimediaKit 1.1
 
Item {
id:preview
 
property alias source:previewImage.source
property Camera camera;
property variant currentImage;
 
signal hide();
 
Image {
width:parent.width;height:parent.height
id:previewImage
}
 
MyButton{
id:shareBtn
anchors.verticalCenter: parent.verticalCenter
anchors.right:parent.right
text:"Share"
enabled: false
 
onClicked: {
console.log("share image"+currentImage);
if( FbHelper.isAuthorized() ) {
FbHelper.uploadPicture(currentImage,"Testing");
} else {
FbHelper.login();
}
}
}
 
Connections{
target: camera
onImageSaved: {
currentImage = path;
preview.source="file://"+path
shareBtn.enabled=true
}
}
}

The image is now captured. The following code allows the user to login to their Facebook account and upload a photo.

[edit] Facebook helper - log in to facebook and upload photos

I created a blog here some time ago, explaining how to login to facebook and how to post comment on wall. I will use same code here to login to facebook account using QNetworkAccessManager.

First of all to login on facebook account and posting on wall or uploading photo, we need to request an application ID from Facebook here. With this id you can request an authorisation token from the Facebook API when you login, and use it to upload photos.

Login method will launch facebook login webpage in QWebView. Once a user enters a valid username and password, it will redirects to https://www.facebook.com/connect/login_success.html url with access token mentioned in query string.

void FacebookHelper::login( const QString& scope ){
QUrl url("https://www.facebook.com/dialog/oauth");
url.addQueryItem("client_id",YOUR_APPP_ID);
url.addQueryItem("redirect_uri",
"https://www.facebook.com/connect/login_success.html");
url.addQueryItem("response_type","token");
url.addQueryItem("scope","read_stream,publish_stream");
 
//view = new QWebView();
view->load( url );
view->show();
connect(view,SIGNAL(loadFinished(bool)),this,SLOT(loginResponse(bool)));
}
 
void FacebookHelper::loginResponse( bool status ){
QUrl url= view->url();
QString strUrl = url.toString();
 
int sIndex = strUrl.indexOf("access_token=");
int eIndex = strUrl.indexOf("&expires_in");
if( sIndex != -1 && eIndex != -1 ){
mAccessToken= strUrl.mid(sIndex, eIndex - sIndex);
mAccessToken = mAccessToken.remove("access_token=");
emit authStatus( mAccessToken);
}
}

Now we have access token, we are ready to upload photo to facebook. Following code describe the process. uploadPicture method takes absolute path to picture to upload and comment for photo, then it creates form-data request and send that to facebook using HTTP Post method.

void FacebookHelper::uploadPicture(const QString& picLocation, const QString& comment) {
 
QString uploadUrl = "https://graph.facebook.com/me/photos?access_token="+ mAccessToken;
 
QFileInfo fileInfo(picLocation);
QFile file(picLocation);
if (!file.open(QIODevice::ReadWrite)) {
qDebug() << "Can not open file:" << picLocation;
return;
}
 
QString bound="---------------------------723690991551375881941828858";
QByteArray data(QString("--"+bound+"\r\n").toAscii());
data += "Content-Disposition: form-data; name=\"action\"\r\n\r\n";
data += "\r\n";
data += QString("--" + bound + "\r\n").toAscii();
data += "Content-Disposition: form-data; name=\"source\"; filename=\""+file.fileName()+"\"\r\n";
data += "Content-Type: image/"+fileInfo.suffix().toLower()+"\r\n\r\n";
data += file.readAll();
data += "\r\n";
data += QString("--" + bound + "\r\n").toAscii();
data += QString("--" + bound + "\r\n").toAscii();
data += "Content-Disposition: form-data; name=\"message\"\r\n\r\n";
data += comment.toAscii();
data += "\r\n";
data += "\r\n";
 
QNetworkRequest request(uploadUrl);
request.setRawHeader(QByteArray("Content-Type"),QString("multipart/form-data; boundary=" + bound).toAscii());
request.setRawHeader(QByteArray("Content-Length"), QString::number(data.length()).toAscii());
mCurrentRequest = mNetManager.post(request,data);
connect(mCurrentRequest,SIGNAL(finished()),this,SLOT(messageResponse()));
}

Once we received finished signal for this request, Photo should appear on user's account.

[edit] Downloads

The project source is here: Media:FacebookHelper.zip. In order to test this you will need to remember to put your Facebook app id, in main.cpp file.

[edit] Summary

By using QML Camera and QNetwokAccessManager we can easily capture and share image to facebook network.

Hope you enjoy the article.

This page was last modified on 11 October 2012, at 04:20.
237 page views in the last 30 days.