Blackberry App, display images from Web - image

I'm using the Blackberry JDE (9000 simulator), and am wondering if I can display an image from the web.
Currently, I'm seeing tutorials that use Bitmap.getBitmapResource to display images that are local to the blackberry application, but looking at the API, I'm not seeing any support for giving a web URL.
Are there other Blackberry image classes I can check out? Or is this feature just not supported?

You can download image using HTTPConnection and InputStream, create EncodedImage from stream and then display it.
See coderholic - Blackberry WebBitmapField
BTW, you can use IOUtilities.streamToBytes() method to read bytes from InputStream directly!

Here is a code example for your problem:
HttpConnection httpConn = null;
InputStream inputStream = null;
int ResponseCode = HttpConnection.HTTP_OK;
byte[] ResponseData = null;
try {
httpConn = (HttpConnection) Connector.open(url, Connector.READ, true);
ResponseCode = httpConn.getResponseCode();
if (ResponseCode == HttpConnection.HTTP_OK) {
inputStream = httpConn.openInputStream();
ResponseData = IOUtilities.streamToBytes(inputStream);
}
}
catch(IOException e){
throw new IOException("HTTP response code: "
+ ResponseCode);
}
finally {
try {
inputStream.close();
inputStream = null;
httpConn.close();
httpConn = null;
}
catch(Exception e){}
}
return ResponseData;

If you want code that made to exactly do this (though this post is old, so I'm guessing you don't anymore)
Here

Related

Xamarin Android image Capture by Camera using intent ActionImageCapture, the image quality is low

Im new to Xamarin Android. Now I was trying to capture the image by camera and displaying in imageview but I was facing the problem which is the image quality that captured from camera is low. And I was doing the research from google and i only found the solution which is save the image that captured in to file and retrieve from file. But the solution is only for android studio and xamarin form.
This is the coding for the intent that calling image captured
Intent intent = new Intent(MediaStore.ActionImageCapture);
StartActivityForResult(intent, 1000);
This is the coding for onactivityresult,
if ((requestCode == PickImageId) && (resultCode == Android.App.Result.Ok) && (data != null))
{
base.OnActivityResult(requestCode, resultCode, data);
bitmap = (Bitmap)data.Extras.Get("data");
var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
string filename = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
string filePath = System.IO.Path.Combine(dir + "/Camera/", filename);
using (var stream = new MemoryStream())
{
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
byte[] bitmapData = stream.ToArray();
try
{
System.IO.File.WriteAllBytes(filePath, bitmapData);
bitmap = BitmapFactory.DecodeByteArray(bitmapData, 0, bitmapData.Length);
imgview.SetImageBitmap(bitmap);
}
catch (Exception ex)
{
System.Console.WriteLine(ex.ToString());
}
}
}
I have try to save the image into phone folder which is 'DCIM/Camera/xxx.jpg'. The image that captured and save in folder is success but the image quality still low.
Is there have any solution to increase the quality of the image?
Sorry for my poor english, please provide me suggestion or solution.
Thanks for giving helps
Hello you can use Xamarin Essential Media Picker to take photo.
Here is an example code:
using Xamarin.Essentials;
string PhotoPath="";
public async Task TakePhotoAsync()
{
try
{
var photo = await MediaPicker.CapturePhotoAsync();
await LoadPhotoAsync(photo);
}
catch (FeatureNotSupportedException fnsEx)
{
// Feature is not supported on the device
}
catch (PermissionException pEx)
{
// Permissions not granted
}
catch (Exception ex)
{
Console.WriteLine($"CapturePhotoAsync THREW: {ex.Message}");
}
}
public async Task LoadPhotoAsync(FileResult photo)
{
// canceled
if (photo == null)
{
PhotoPath = null;
return;
}
// save the file into local storage
var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName); //or any other Storage Directory
using (var stream = await photo.OpenReadAsync())
using (var newStream = File.OpenWrite(newFile))
await stream.CopyToAsync(newStream);
PhotoPath = newFile;
}

Generating pdf in a web API (ItextSharp 5.5.13)

I need to create a PDF file in memory within a web API and send it. I do create the PDF and the web API sends it, but I can't open it once received.
I do create the PDF as a byte array with this:
private byte[] createPDF()
{
MemoryStream memStream = new MemoryStream();
byte[] pdfBytes;
Document doc = new Document(iTextSharp.text.PageSize.LETTER);
PdfWriter wri = PdfWriter.GetInstance(doc, memStream);
doc.AddTitle("test");
doc.AddCreator("I am");
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
pdfBytes = memStream.ToArray();
doc.Close(); //Close
return pdfBytes;
}
This method is called by the method in the web API which sends the PDF, and it is this one:
[HttpGet]
public HttpResponseMessage GetFiniquitopdf()
{
try
{
byte[] buffer = createPDF();
response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(new MemoryStream(buffer));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentLength = buffer.Length;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "myFirstPDF.pdf"
};
}
catch (Exception e)
{
response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
return response;
}
The problem is when the PDF is downloaded it is useless, can't be opened, I don't understand why the PDF can't be opened, I thought it was the security of the Windows 10, so once downloaded I do check it as a secure file, but it doesn't open anyway.
I guess there is something wrong in the way I send it or maybe I lack of something in the creation of the PDF file
thanks in advance
You retrieve the bytes from the memory stream before closing the document:
pdfBytes = memStream.ToArray();
doc.Close(); //Close
return pdfBytes;
But the pdf in the memory stream is not complete before the document is closed. Thus, simply switch the order of instructions:
doc.Close(); //Close
pdfBytes = memStream.ToArray();
return pdfBytes;

Get image from standard Android Gallery

I am having problems getting an image back from the default android gallery. All I want to do is call the Android standard gallery intent and return the uri for the image in my onActivityResult. When I run this code it open the gallery just fine but then it force closes whenever I click on a picture. Any tips for this would be helpful.
private void doGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setType(IJudgeSingleton.IMAGEINTENT);
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "Select Picture"), IJudgeSingleton.REQUEST_CODE_GALLERY);
}
case IJudgeSingleton.REQUEST_CODE_GALLERY:
Uri uri = data.getData();
mSingleton.mFileTemp = new File(getMediaPath(uri));
try {
IJudgeSingleton.copy(mSingleton.mFileTemp, mSingleton.mCropFileTemp);
mData.setImageSet(true, mSingleton.mFileTemp.toURI().toString(), true);
mData.setPhoto(true);
}
catch (IOException e) {
Log.d(this.getClass().getName(), "REQUEST_CODE_GALLERY", e);
}
break;
Figured it out my file was pointing to a null so that's what was giving me the force close. Also I had to add change some code around in my onActivityResult for REQUEST_CODE_GALLERY. I have posted the added code below for anyone who has this problem.
case IJudgeSingleton.REQUEST_CODE_GALLERY:
Uri uri = data.getData();
//This takes the uri/image returned from the gallery intent a places it into a file.
final int chunkSize = 1024; // We'll read in one kB at a time
byte[] imageData = new byte[chunkSize];
try {
InputStream in = getContentResolver().openInputStream(uri);
OutputStream out = new FileOutputStream(mSingleton.mFileTemp); // I'm assuming you already have the File object for where you're writing to
int bytesRead;
while ((bytesRead = in.read(imageData)) > 0) {
out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead)));
}
in.close();
out.close();
} catch (Exception ex) {
Log.e(this.getClass().getName(),"REQUEST_CODE_GALLERY");
}
// mSingleton.mFileTemp = new File(getMediaPath(uri));
try {
IJudgeSingleton.copy(mSingleton.mFileTemp, mSingleton.mCropFileTemp);
mData.setImageSet(true, mSingleton.mFileTemp.toURI().toString(), true);
mData.setPhoto(true);
}
catch (IOException e) {
Log.d(this.getClass().getName(), "REQUEST_CODE_GALLERY", e);
}
break;
case IJudgeSingleton.REQUEST_CODE_DEFAULT_CAPTURE:
mData = data.getParcelableExtra(IJudgeSingleton.SURVEY_INTENT);
showListView();
completedIntent = false;

HtmlUnit Save Image Quality

I'm creating code to download some images from the web using HtmlUnit.
But when I save the image with HtmlUnit the quality of the image is very low compared with the original image.
I used this code to save the img url to a file.
try {
HtmlImage imgX = (HtmlImage)
page.getByXPath("//img").get(0);
Thread.sleep(3000);
File imageFile = new File(dir +"/"+ name);
imgX.saveAs(imageFile);
System.out.println("Done!!!!");
} catch (Exception e) {
e.printStackTrace();
}
Are there other options to get the image with the best quality?
I tried using this:
How to convert an <img... in html to byte [] in Java
But the image was not created.
Get the WebResponse from HtmlImage:
InputStream inputStream = imgX.getWebResponse(true).getContentAsStream();
And then work directly on InputStream:
File imageFile = new File(dir +"/"+ Name);
FileOutputStream outputStream = new FileOutputStream(imageFile);
IOUtils.copy(inputStream, outputStream);

Sending Image with Exif info from Windows Phone to Java Server

I'm new in programming in Windows Phone (and StackOverflow tbh). Currently, I'm working on a task that concerns with sending images stored in the Windows Phone's storage (with Exif info) to a Java server. So far I have successfully send the byte stream from the Windows Phone client and construct the image on the Java side, however, the Exif information is somehow lost. I believe it's just the way I send it on Windows Phone that's causing the problem. Very much appreciated for any help or guidance !
Here's my code on the Windows Phone client:
// Windows Phone Client code (MainPage.xaml.cs)
// This function is called when an image is selected from
// the task PhotoChooserTask ptask, which brings
// a popup that allows the user to choose an image
// from the phone's storage
void ptask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK && e.ChosenPhoto != null)
{
//Take JPEG stream and decode into a WriteableBitmap object
App.CapturedImage = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
// Attempt to send the image
WriteableBitmap pic = new WriteableBitmap(App.CapturedImage);
MemoryStream stream = new MemoryStream();
pic.SaveJpeg(stream, App.CapturedImage.PixelHeight, App.CapturedImage.PixelWidth, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
client.Send(stream);
// Close the socket connection explicitly
client.Close();
}
}
Here's the code in the SocketClient.cs
public string Send(MemoryStream data)
{
byte[] msData = data.ToArray();
if (_socket != null)
{
// Create SocketAsyncEventArgs context object
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
// Set properties on context object
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
socketEventArg.UserToken = null;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
_clientDone.Set();
});
// Add the data to be sent into the buffer
socketEventArg.SetBuffer(msData, 0, msData.Length);
// Sets the state of the event to nonsignaled, causing threads to block
_clientDone.Reset();
// Make an asynchronous Send request over the socket
_socket.SendAsync(socketEventArg);
}
else
{
response = "Socket is not initialized";
}
return response;
}
On the Java Server,
public static void main(String[] args) {
ServerSocket serverSocket;
Socket client;
try {
serverSocket = new ServerSocket(PORT_NUMBER);
while (true) {
client = serverSocket.accept();
// Extract exif info
InputStream inputStream = client.getInputStream();
InputStream stream = new BufferedInputStream(inputStream);
// Create file from the inputStream
File file = new File("image.jpg");
try {
OutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[4096];
for (int n; (n = stream.read(buffer)) != -1;) {
os.write(buffer, 0, n);
}
}
The output image is identical to the one sent from the windows phone, just without any Exif information whatsoever. Anyone could point out what I did wrong that causes the information to be lost? I'm guessing because I called the SaveJpeg function in the windows phone code, rewriting the image file, and losing all information there, but I don't know how else to convert the image to byte and stream it.
Much help is appreciated ! Thank you.
I found the answer to my own problem. For those of you who might have a problem with this. I simply use:
Byte[] imageData = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Position = 0;
e.ChosenPhoto.Read(imageData, 0, imageData.Length);
Then send the byte array in my send function:
socketEventArg.SetBuffer(imageData, 0, imageData.Length);

Resources