Post Image from Blackberry WebWorks SDK Camera to PHP File Server - image

I am using Blackberry webworks i want to upload image from camera to php webserver i am getting image in uri and it is displaying correctly but i dont know how to upload image to server please help.
file uri
file://dir/image name
i am using this code from blackberry webworks camera api
function takePicture() {
try {
blackberry.media.camera.takePicture(photoTaken, closedCB, errorCB);
} catch (e) {
//alert("Error in supported: " + e);
}
}
function successCB(filePath) {
var file = "file://" + filePath;
$("#myfileCam").val(file);
$("#imgPic").show();
$("#imgPic").attr("src", file);
}
function photoTaken(filePath) {
var img = new Image();
img.src = "file://" + filePath;
img.width = Math.round(screen.width / 2);
document.getElementById("path").appendChild(img);
var html = "<input type='file' name='myfile' id='myfile' value='file://" + filepath + "' />";
document.getElementById("fileup").innerHTML = html;
//$("#fileup").html();
$("#myfileCam").val("file://" + filePath);
}
function closedCB() {
// alert("Camera closed event");
}
function errorCB(e) {
alert("Error occured: " + e);
}

FileConnection fc= (FileConnection)Connector.open(filePath);
InputStream is=fc.openInputStream();
byte[] ReimgData = IOUtilities.streamToBytes(is);
EncodedImage encode_image =EncodedImage.createEncodedImage(ReimgData, 0, (int)fc.fileSize());
JPEGEncodedImage encoder=JPEGEncodedImage.encode(encode_image.getBitmap(),50);
byte[] array=encoder.getData();
// Decodes the image represented by this EncodedImage and returns a Bitmap
int length=array.length;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(length);
Base64OutputStream base64OutputStream = new Base64OutputStream( byteArrayOutputStream );
try{
base64OutputStream.write( array, 0, length );
base64OutputStream.flush();
base64OutputStream.close();
}
catch (IOException ioe){
//Dialog.alert("Error in encodeBase64() : "+ioe.toString());
System.out.println("Error in encodeBase64() : "+ioe.toString());
}
data = Base64InputStream.decode(byteArrayOutputStream.toString());

Use Phonegap for Blackberry Webworks I had the same problem and i resolved using this api.
http://docs.phonegap.com/en/1.5.0/phonegap_file_file.md.html#FileTransfer here everything you need.
The only thing you need to do is to put the phonegap jar file in ext folder and call for permissions en config.xml adding this feature (phonegap), and that it.
I hope this work to you, it worked to me.

Related

Rgb 565 Pdf to Image

I am trying to convert a PDF page to an image, to create thumbnails. This is the code that I am using:
PdfRenderer pdfRenderer = new PdfRenderer(GetSeekableFileDescriptor(filePath));
var appDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
string fileName = System.IO.Path.GetFileNameWithoutExtension(filePath);
string directoryPath = System.IO.Path.Combine(appDirectory, "thumbnailsTemp", System.IO.Path.GetFileNameWithoutExtension(fileName));
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
int pageCount = pdfRenderer.PageCount;
for (int i = 0; i < pageCount; i++)
{
Page page = pdfRenderer.OpenPage(i);
Android.Graphics.Bitmap bmp = Android.Graphics.Bitmap.CreateBitmap(page.Width, page.Height, Android.Graphics.Bitmap.Config.Rgb565 or Argb8888);
page.Render(bmp, null, null, PdfRenderMode.ForDisplay);
try
{
using (FileStream output = new FileStream(System.IO.Path.Combine(directoryPath, fileName + "Thumbnails" + i + ".png"), FileMode.Create))
{
bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, output);
}
page.Close();
}
catch (Exception ex)
{
//TODO -- GERER CETTE EXPEXPTION
throw new Exception();
}
}
return directoryPath;
}
I tried with ARGB 8888 and that was a success. But the rendering time was too slow for big PDF files. This is why I tried to improve it by changing the format to RGB 565. But my app is crashing with this Execption:
Unsuported pixel format
Any idea to fix this, or how to render a PDF to a bitmap faster? I was looking on google but didn't find a solution related to my code.
UPDATE
I did this but know, my app is crashing at this line of code :
await Task.Run(() =>
{
bytes = page.AsPNG(72);
});
My class :
public async Task<string> GetBitmaps(string filePath)
{
//TODO -- WORK ON THIS
PdfRenderer pdfRenderer = new PdfRenderer(GetSeekableFileDescriptor(filePath));
var appDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
string fileName = System.IO.Path.GetFileNameWithoutExtension(filePath);
string directoryPath = System.IO.Path.Combine(appDirectory, "thumbnailsTemp", System.IO.Path.GetFileNameWithoutExtension(fileName));
var stream = new MemoryStream();
using (Stream resourceStream = new FileStream(filePath, FileMode.Open))
{
resourceStream.CopyTo(stream);
}
for (int i = 0; i < pdfRenderer.PageCount; i++)
{
TallComponents.PDF.Rasterizer.Page page = new TallComponents.PDF.Rasterizer.Page(stream, i);
byte[] bytes = null;
await Task.Run(() =>
{
bytes = page.AsPNG(72);
});
using (FileStream output = new FileStream(System.IO.Path.Combine(directoryPath, fileName + "Thumbnails" + i + ".png"), FileMode.Create, FileAccess.Write))
{
output.Write(bytes, 0, bytes.Length);
}
}
return directoryPath;
}
you could draw a PDF page in app by converting a PDF page to a bitmap,here the PDF document itself is embedded as a resource.
var assembly = Assembly.GetExecutingAssembly();
var stream = new MemoryStream();
using (Stream resourceStream = assembly.GetManifestResourceStream("DrawPdf.Android.tiger.pdf"))
{
resourceStream.CopyTo(stream);
}
Page page = new Page(stream, 0);
// render PDF Page object to a Bitmap
byte[] bytes = null;
await Task.Run(() =>
{
bytes = page.AsPNG(72);
});
Bitmap bmp = global::Android.Graphics.BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length);

Android post image to Facebook comment

This is a followup to my previous question: Xamarin.Forms App return data to calling App
That works perfectly and I can share images to anywhere, except to Facebook comments. When I click the camera on the content box the app can be selected, I can select the image, Set result and Finish are called, and the app closes and it sends data to Facebook, and then however I then get the error : The image could not be uploaded, try again?
I can't find any fundamental differences between posting to a status or a comment, so I'm guessing it's subtle. Any thoughts on how I can change my intent to post properly?
Adding for completeness:
Bitmap b = null;
string url;
if (!string.IsNullOrEmpty(this.saleItems[i].ImageUrl))
{
url = this.saleItems[i].ImageUrl;
}
else
{
url = await FileHelper.GetLocalFilePathAsync(this.saleItems[i].Id);
}
//download
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
b = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
//set local path
var tempFilename = "test.png";
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePath = System.IO.Path.Combine(sdCardPath, tempFilename);
using (var os = new FileStream(filePath, FileMode.Create))
{
b.Compress(Bitmap.CompressFormat.Png, 100, os);
}
b.Dispose();
var imageUri = Android.Net.Uri.Parse($"file://{sdCardPath}/{tempFilename}");
var sharingIntent = new Intent();
sharingIntent.SetAction(Intent.ActionSend);
sharingIntent.SetType("image/*");
sharingIntent.PutExtra(Intent.ExtraText, "some txt content");
sharingIntent.PutExtra(Intent.ExtraStream, imageUri);
sharingIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
//await SaleItemDataService.Instance.BuySaleItemAsync(this.saleItem);
SetResult(Result.Ok, sharingIntent);
Finish();
Use below:
Intent sharingIntent = new Intent();
string imageUri = "file://" + requestedUri;
sharingIntent.SetData(Android.Net.Uri.Parse(imageUri));

Upload a file to specific folderid using REST Api

I've searched all documents in google drive api and I can't able to find how to upload a file to folderid using REST APi. Can anyone please help me on this?
public void UploadFiletoDrive()
{
var gmodel = GetAccessToken();
WebRequest request = WebRequest.Create("https://www.googleapis.com/upload/drive/v3/files/?uploadType=media");
request.Method = "POST";
request.Headers["Authorization"] = "Bearer " + gmodel.access_token;
request.ContentType = "image/jpeg";
Stream dataStream = request.GetRequestStream();
FileStream filestream = new FileStream(#"C:\Users\Developer\Downloads\unnamed (2).jpg", FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = filestream.Read(buffer, 0, buffer.Length)) != 0)
{
dataStream.Write(buffer, 0, bytesRead);
}
filestream.Close();
dataStream.Close();
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseFromServer = reader.ReadToEnd();
reader.Close();
response.Close();
}
It seems you've missed the Work with Folders docs.
Inserting a file in a folder using Java:
String folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E";
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
fileMetadata.setParents(Collections.singletonList(folderId));
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id, parents")
.execute();
System.out.println("File ID: " + file.getId());
Implementation for other languages are also included like PHP, Python, NodeJS.
Also, check this SO thread for additional reference.
body.setParents(Arrays.asList(new ParentReference().setId(folderId)));
Your sample code is doing a media upload, ie. no metadata, You should be using a multipart upload so you can specify both metadata such as parent folder id and content.
Uploading a file to google drive using REST API has following steps.
Get parent folderID using list API
Create file with parent="folder ID" using create api and get "fileId" in response
upload file to "fileId
Following is javascript code to upload file using REST API
const url = 'https://www.googleapis.com/upload/drive/v3/files/' + fileId + '?uploadType=media';
if(self.fetch){
// console.log("Fetch found, Using fetch");
var setHeaders = new Headers();
setHeaders.append('Authorization', 'Bearer ' + authToken.access_token);
setHeaders.append('Content-Type', mime);
var setOptions = {
method: 'PATCH',
headers: setHeaders,
body: blob
};
fetch(url,setOptions)
.then(response => { if(response.ok){
// console.log("save to google using fetch");
}
else{
// console.log("Response wast not ok");
}
})
.catch(error => {
// console.log("There is an error " + error.message);
});
}

Xamarin.Forms Android save image to gallery

I have a stream which is the result of taking a photo. I want to save that photo to the users Gallery.
I have tried all manner of things but nothing takes... The class I am saving is a plain C# class - it does not inherit form any android types but that could be done if necessary (to fire an intent perhaps - though I tried this and it ended up another rabbit hole)
I have tried this:
try{
using (FileStream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + _name, FileMode.OpenOrCreate))
{
fs.Write(bytes, 0, bytes.Length);
}
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
and also:
if (_filename.ToLower ().Contains (".jpg") || _filename.ToLower ().Contains (".png")) {
stream.Position = 0;
var bitmap = BitmapFactory.DecodeStream (stream);
var finalStream = new MemoryStream ();
bitmap.Compress (Bitmap.CompressFormat.Jpeg, 25, finalStream);
bitmap = null;
finalStream.Position = 0;
var path2 = Environment.GetFolderPath (Environment.SpecialFolder.MyPictures);
var filename2 = System.IO.Path.Combine (path2, _filename);
using (var fileStream = File.Create (filename2)) {
finalStream.Seek (0, SeekOrigin.Begin);
finalStream.CopyTo (fileStream);
fileStream.Close ();
finalStream.Dispose ();
stream.Dispose ();
fileStream.Dispose ();
GC.Collect ();
}
return;
}
I thought this would be an easy task! meh...
Any help?
Use the MediaStore ContentProvider. MediaStore.Images.Media has several Insert methods you can use to add content to the gallery.

ABCPDF 8 - How do I create a layered PDF

I need to use ABCPDF to create a layered PDF file. I've seen examples for watermarks but I need to have a PDF be the second layer. My code is below. When I run it, I only see one layer. What am I doing incorrectly?
Thank you.
WebSupergoo.ABCpdf8.Doc artworkDoc = new WebSupergoo.ABCpdf8.Doc();
artworkDoc.SetInfo(0, "License", _License);
WebSupergoo.ABCpdf8.Doc cutDoc = new WebSupergoo.ABCpdf8.Doc();
cutDoc.SetInfo(0, "License", _License);
// Attempt to read in Artwork File
try
{
artworkDoc.Read(ArtworkPath);
}
catch (Exception ex)
{
Exception noartwork = new Exception("Problem with Artwork File: " + ex.ToString());
throw noartwork;
}
// Attempt to read in cut File
try
{
cutDoc.Read(cutPath);
}
catch (Exception ex)
{
Exception nocut = new Exception("Problem with cut File: " + ex.ToString());
throw nocut;
}
WebSupergoo.ABCpdf8.Doc outputDoc = artworkDoc;
outputDoc.SetInfo(0, "License", _License);
// Attempt to merge artwork and cut files into output Document
try
{
outputDoc.PageNumber = 1;
outputDoc.Layer = outputDoc.LayerCount + 1;
outputDoc.AddImageDoc(cutDoc, 1, outputDoc.Rect);
}
catch (Exception ex)
{
Exception problem = new Exception("Problem appending cut and artwork files to output: " + ex.ToString());
throw problem;
}
// Attempt to save the output Document to the specified output path
try
{
outputDoc.Save(OutputPath);
artworkDoc.Clear();
cutDoc.Clear();
outputDoc.Clear();
}
catch (Exception ex)
{
Exception invalidOutput = new Exception("Unable to write output file: " + ex.ToString());
throw invalidOutput;
}
return true;
}
After resorting to using iTextSharp for some other PDF layer issues I had, I decided to explore how to use iTextSharp to create a new layered PDF file where the layers are pages from existing PDF files. The below code is what I came up with. The code presumes each of the source PDF files only has one page to add as a layer to the new PDF. It took me awhile to figure out so hopefully posting it here will help save others some time.
try
{
iTextSharp.text.pdf.PdfReader artwork = new iTextSharp.text.pdf.PdfReader(#”c:\artwork.pdf”);
iTextSharp.text.pdf.PdfReader cut = new iTextSharp.text.pdf.PdfReader(#”c:\cut.pdf”);
//get size of the cut PDF so the new layered PDF will be sized the same.
iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(cut.GetPageSize(1).Width, cut.GetPageSize(1).Height);
//the artwork PDF needs to be sized the same as the cut pdf
if (artwork.GetPageSize(1).Width != pageSize.Width || artwork.GetPageSize(1).Height != pageSize.Height)
{
string resizedFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(textBox1.Text),System.IO.Path.GetFileNameWithoutExtension(textBox1.Text) + "_resized.pdf");
iTextSharp.text.Document resizedArtwork = new iTextSharp.text.Document(pageSize);
iTextSharp.text.pdf.PdfWriter resizedWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(resizedArtwork, new System.IO.FileStream(resizedFile, System.IO.FileMode.Create));
iTextSharp.text.pdf.PdfImportedPage importedPage = resizedWriter.GetImportedPage(artwork, 1);
resizedArtwork.Open();
iTextSharp.text.pdf.PdfContentByte resizedContentByte = resizedWriter.DirectContent;
resizedContentByte.AddTemplate(importedPage, 0, 0);
resizedArtwork.Close();
//close reader associated with non-resized document
artwork.Close();
//set reader to resized document
artwork = new iTextSharp.text.pdf.PdfReader(resizedFile);
}
//create a new PDF
string outputFileName = #”c:\layered.pdf”;
iTextSharp.text.Document newPDF = new iTextSharp.text.Document(pageSize);
//create writer to output new PDF's contents to
iTextSharp.text.pdf.PdfWriter pdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(newPDF, new System.IO.FileStream(outputFileName,System.IO.FileMode.Create));
//grab the first page from the artwork and cut PDF. These will become new layers in the new PDF
iTextSharp.text.pdf.PdfImportedPage artworkImportedPage = pdfWriter.GetImportedPage(artwork, 1);
iTextSharp.text.pdf.PdfImportedPage cutImportedPage = pdfWriter.GetImportedPage(cut, 1);
newPDF.Open();
iTextSharp.text.pdf.PdfContentByte pdfContentByte = pdfWriter.DirectContent;
pdfContentByte.BeginLayer(new iTextSharp.text.pdf.PdfLayer("artwork",pdfWriter));
pdfContentByte.AddTemplate(artworkImportedPage, 0, 0);
pdfContentByte.EndLayer();
pdfContentByte.BeginLayer(new iTextSharp.text.pdf.PdfLayer("cut", pdfWriter));
pdfContentByte.AddTemplate(cutImportedPage, 0, 0);
pdfContentByte.EndLayer();
newPDF.Close();
pdfWriter.Close();
artwork.Close();
cut.Close();
}
catch (Exception ex)
{
}

Resources