Blackberry - ListField with images from filesystem - image

I use the following code to retrieve image from the phone or SDCard and I use that image in to my ListField. It gives the output but it takes very Long time to produce the screen. How to solve this problem ?? Can any one help me?? Thanks in advance!!!
String text = fileholder.getFileName();
try{
String path="file:///"+fileholder.getPath()+text;
//path=”file:///SDCard/BlackBerry/pictures/image.bmp”
InputStream inputStream = null;
//Get File Connection
FileConnection fileConnection = (FileConnection) Connector.open(path);
inputStream = fileConnection.openInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while((j=inputStream.read()) != -1) {
baos.write(j);
}
byte data[] = baos.toByteArray();
inputStream.close();
fileConnection.close();
//Encode and Resize image
EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length);
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(180));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP(180));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
Bitmap bitmapImage = eImage.getBitmap();
graphics.drawBitmap(0, y+1, 40, 40,bitmapImage, 0, 0);
graphics.drawText(text, 25, y,0,width);
}
catch(Exception e){}

You should read files once (on App start or before screen open, maybe put a progress dialog there), put images in array and use this array in paint.

Related

How do I set LogicalScreenDescriptor and ImageDescriptor gif metadata

I want to create a GIF with a Logical Screen Descriptor larger than any image that I have in my gif image sequence. Each image in the gif will have its top and left offset modified. Here's the code I have that looks like it ought to work, but it doesn't
void test() throws IOException {
Image image1 = textToImage ("m",12.0 );
Image image2 = textToImage("n", 24.0);
Image[] images = {image2, image1};
String[] imageTopOffset = {"6", "30"};
String[] imageLeftOffset = {"6", "36"};
ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next();
ImageWriteParam params = iw.getDefaultWriteParam();
int type = ((BufferedImage)getRenderedImage(image1)).getType();
ImageTypeSpecifier imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(type);
IIOMetadata metadata = iw.getDefaultImageMetadata(imageTypeSpecifier, params);
IIOMetadataNode root = (IIOMetadataNode)metadata.getAsTree(metadata.getNativeMetadataFormatName());
IIOMetadataNode lsdNode = getNode(root, "LogicalScreenDescriptor");
lsdNode.setAttribute("logicalScreenHeight", "100");
lsdNode.setAttribute("logicalScreenWidth", "75");
IIOMetadataNode graphicsControlExtensionNode = getNode(root, "GraphicControlExtension");
graphicsControlExtensionNode.setAttribute("disposalMethod", "none");
graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE");
graphicsControlExtensionNode.setAttribute("transparentColorFlag", "FALSE");
graphicsControlExtensionNode.setAttribute("delayTime", "100");
graphicsControlExtensionNode.setAttribute("transparentColorIndex", "0");
IIOMetadataNode commentsNode = getNode(root, "CommentExtensions");
commentsNode.setAttribute("CommentExtension", "Created by: http://example.com");
IIOMetadataNode appExtensionsNode = getNode(root, "ApplicationExtensions");
IIOMetadataNode child = new IIOMetadataNode("ApplicationExtension");
child.setAttribute("applicationID", "NETSCAPE");
child.setAttribute("authenticationCode", "2.0");
boolean loop = true;
int loopContinuously = loop ? 0 : 1;
child.setUserObject(new byte[]{ 0x1, (byte) (loopContinuously & 0xFF), (byte) ((loopContinuously >> 8) & 0xFF)});
appExtensionsNode.appendChild(child);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
iw.setOutput(ios);
iw.prepareWriteSequence(metadata);
int i = 0;
for (Image image : images) {
graphicsControlExtensionNode = getNode(root, "GraphicControlExtension");
graphicsControlExtensionNode.setAttribute("delayTime", "50");
IIOMetadataNode imageDescriptorNode = getNode(root, "ImageDescriptor");
imageDescriptorNode.setAttribute("imageLeftPosition", imageLeftOffset[i]);
imageDescriptorNode.setAttribute("imageTopPosition", imageTopOffset[i]);
imageDescriptorNode.setAttribute("imageWidth", String.valueOf(image.getWidth()));
imageDescriptorNode.setAttribute("imageHeight", String.valueOf(image.getHeight()));
imageDescriptorNode.setAttribute("interlaceFlag", "FALSE");
IIOImage ii = new IIOImage(getRenderedImage(image), null, metadata);
iw.writeToSequence(ii, params);
i++;
}
iw.endWriteSequence();
ios.close();
byte[] gifContent = os.toByteArray();
os.close();
File outputFile = new File("test.gif");
try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
outputStream.write(gifContent);
outputStream.close();
}
}
private WritableImage textToImage(String text, Double size) {
Text t = new Text();
t.setFont(getFont("Calibi",
"NORMAL",
"REGULAR",
size));
t.setStroke(Color.BLACK);
t.setText(text);
Scene scene = new Scene(new StackPane(t));
return t.snapshot(null, null);
}
IIOMetadataNode getNode(IIOMetadataNode rootNode, String name) {
NodeList childNodes = rootNode.getChildNodes();
for (int i=0; i<childNodes.getLength(); i++) {
if (childNodes.item(i).getNodeName().equals(name) ) {
return (IIOMetadataNode)childNodes.item(i);
}
}
// no child node with the given name found, create one!
IIOMetadataNode metadataNode = new IIOMetadataNode(name);
rootNode.appendChild(metadataNode);
return metadataNode;
}
Font getFont(String fontname, String fontWeight, String fontPosture, double size) {
FontPosture posture = FontPosture.valueOf(fontPosture);
FontWeight weight = FontWeight.valueOf(fontWeight);
Font font = Font.font (fontname, weight, posture, size);
return font;
}
public RenderedImage getRenderedImage(Image image) {
return SwingFXUtils.fromFXImage(image, null);
}
The gif image it produces is the size of the first image in the sequence even though I set the LogicalScreenDescriptor to a bigger size than the image that gets written out. The actual size of the gif is the size of the 1st image. The other problem is that imageTopPosition and imageLeftPosition doesn't get applied.
The two images are of different sizes. The two images are generated, one image is a 12 point image of the letter m, and the other image is a 24 point image of the letter n.
So how do I make a larger logical screen descriptor and how do I change the image descriptor offsets. Although the above code looks like it should work, it doesn't. Most examples I've found assume that all images in a gif are the same size and that the display of subsequent images in the gif completely replace the previous image.
Here are the coding changes I made that solved the problem for the gif not displaying properly:
void test() throws IOException {
Image image1 = textToImage ("m",12.0 );
Image image2 = textToImage("n", 24.0);
Image[] images = {image2, image1};
String[] imageTopOffset = {"6", "30"};
String[] imageLeftOffset = {"6", "36"};
ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/gif").next();
ImageWriteParam params = iw.getDefaultWriteParam();
int type = ((BufferedImage)getRenderedImage(image1)).getType();
ImageTypeSpecifier imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(type);
IIOMetadata imageMetadata = iw.getDefaultImageMetadata(imageTypeSpecifier, params);
IIOMetadata streamMetadata = iw.getDefaultStreamMetadata(params);
IIOMetadataNode streamRoot = (IIOMetadataNode)streamMetadata.getAsTree(streamMetadata.getNativeMetadataFormatName());
IIOMetadataNode imageRoot = (IIOMetadataNode)imageMetadata.getAsTree(imageMetadata.getNativeMetadataFormatName());
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
iw.setOutput(ios);
IIOMetadataNode lsdNode = getNode(streamRoot, "LogicalScreenDescriptor");
lsdNode.setAttribute("logicalScreenHeight", "100");
lsdNode.setAttribute("logicalScreenWidth", "75");
/*
* The following extension nodes may not be put in the streamMetadata. If you do add them
* to the streamMetadata you'll get any error when you prepareWriteSequence
*
IIOMetadataNode graphicsControlExtensionNode = getNode(streamRoot, "GraphicControlExtension");
graphicsControlExtensionNode.setAttribute("disposalMethod", "none");
graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE");
graphicsControlExtensionNode.setAttribute("transparentColorFlag", "FALSE");
graphicsControlExtensionNode.setAttribute("delayTime", "100");
graphicsControlExtensionNode.setAttribute("transparentColorIndex", "0");
IIOMetadataNode commentsNode = getNode(streamRoot, "CommentExtensions");
commentsNode.setAttribute("CommentExtension", "Created by: http://example.com");
IIOMetadataNode appExtensionsNode = getNode(streamRoot, "ApplicationExtensions");
IIOMetadataNode child = new IIOMetadataNode("ApplicationExtension");
child.setAttribute("applicationID", "NETSCAPE");
child.setAttribute("authenticationCode", "2.0");
boolean loop = true;
int loopContinuously = loop ? 0 : 1;
child.setUserObject(new byte[]{ 0x1, (byte) (loopContinuously & 0xFF), (byte) ((loopContinuously >> 8) & 0xFF)});
appExtensionsNode.appendChild(child);
*/
streamMetadata.setFromTree(streamMetadata.getNativeMetadataFormatName(), streamRoot);
iw.prepareWriteSequence(streamMetadata);
int i = 0;
for (Image image : images) {
IIOMetadataNode graphicsControlExtensionNode = getNode(imageRoot, "GraphicControlExtension");
graphicsControlExtensionNode.setAttribute("delayTime", "50");
IIOMetadataNode imageDescriptorNode = getNode(imageRoot, "ImageDescriptor");
imageDescriptorNode.setAttribute("imageLeftPosition", imageLeftOffset[i]);
imageDescriptorNode.setAttribute("imageTopPosition", imageTopOffset[i]);
imageMetadata.setFromTree(imageMetadata.getNativeMetadataFormatName(),imageRoot);
IIOImage ii = new IIOImage(getRenderedImage(image), null, imageMetadata);
iw.writeToSequence(ii, params);
i++;
}
iw.endWriteSequence();
ios.close();
byte[] gifContent = os.toByteArray();
os.close();
File outputFile = new File("test.gif");
try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
outputStream.write(gifContent);
outputStream.close();
}
}
The prepareWriteSequence command did not like streamMetadata that contains the extensions graphicControlExtension and ApplicationExtensions. I figured that out by examining the source code for GifImageWriter. There's also some problem with the value I provided to the set "imageWidth and "imageHeight". Not sure what the value for those attributes should look like. I just avoid that problem by not setting those values.
The output is a 75x100 gif with a 12pt letter m offset by 30 from the top and 36 from the left and a 24 point letter n offset 6 from the top and 6 from the left.

Why is part of the image cut out when taking a picture with this code on Blackberry?

When I take a picture on the simulator (Haven't tried a device yet) the result is only less than half of the image and the rest is gray. Does anyone know why?
Thanks
listener = new FileSystemJournalListener()
{
private long _lastUSN;
public void fileJournalChanged()
{
long nextUSN = FileSystemJournal.getNextUSN();
FileSystemJournalEntry entry = FileSystemJournal.getEntry(nextUSN - 1);
nextUSN++;
switch (entry.getEvent()) {
case FileSystemJournalEntry.FILE_ADDED:
try
{
FileConnection fconn = (FileConnection)Connector.open("file://" +entry.getPath());
if(fconn.exists())
{
InputStream input = null;
input = fconn.openInputStream();
byte[] data = new byte[(int) fconn.fileSize() + 1000];
input.read(data);
rawImage = data;
pic = Bitmap.createBitmapFromBytes(data, 0, -1, 1);
if(input != null)
{
input.close();
}
Bitmap[] images = new Bitmap[1];
images[0] = pic;
//labels[1] = "Label for image 2";
// tooltips[1] = "Tooltip for image 2";
// labels[2] = "Label for image 2";
// tooltips[2] = "Tooltip for image 2";
ScrollEntry[] entries = new ScrollEntry[images.length];
entries[0] = new ScrollEntry(images[0], "", "");
PictureScrollField pictureScrollField = new PictureScrollField(175, 131);
pictureScrollField.setData(entries, 0);
pictureScrollField.setHighlightStyle(HighlightStyle.ILLUMINATE_WITH_SHRINK_LENS);
// pictureScrollField.setHighlightBorderColor(Color.BLUE);
pictureScrollField.setBackground(BackgroundFactory.createSolidTransparentBackground(Color.BLACK, 150));
insert(pictureScrollField, 1);
picTaken = true;
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE, 0, 50);
inject.post();
inject.post();
}
break;
}
catch (Exception e)
{
// TODO Auto-generated catch block
Dialog.alert(e.toString());
}
//either a picture was taken or a picture was added to the BlackBerry device
case FileSystemJournalEntry.FILE_DELETED:
//a picture was removed from the BlackBerry device;
break;
}
input.read(data) only reads some amount of data, not all of it. If you want to read the whole file, use IOUtilities.streamToBytes(input); instead, like this:
byte[] data = IOUtilities.streamToBytes(input);
byte[] data = new byte[(int) fconn.fileSize() + 1000];
...
pic = Bitmap.createBitmapFromBytes(data, 0, -1, 1);
I think data now contains last wrong 1000 bytes, try changing to:
byte[] data = new byte[(int) fconn.fileSize()];
I faced the same problem. Just use:
synchronized(UiApplication.getEventLock()) {
//your code here
}

Blackberry - get image data from bitmap

how to get image data from a bitmap image ? i searched, but i cant find a solution
int height=bmp.getHeight();
int width=bmp.getWidth();
int[] rgbdata = new int[width*height];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
//Graphics g = new Graphics(bmp);
bmp.getARGB(rgbdata,0,width,0,0,width,height);
for (int i = 0; i < rgbdata.length ; i++) {
if (rgbdata[i] != -1)
{
dos.writeInt(rgbdata[i]);
dos.flush();
}
}
bos.flush();
Try this:
PNGEncoder encoder = new PNGEncoder(bitmap, true);
byte[] imageBytes = encoder.encode(true);
And to get EncodedImage from byte array:
EncodedImage fullImage = EncodedImage.createEncodedImage(imageBytes, 0, imageBytes.length);

Monodroid save image from url

Hello the app that I'm building works with alot of images that are stored on the server and need to display them on a listview. I would like to be able to store them on a file.
so far here is the code I have
var imageUrl = new Java.Net.URL(obj.imageUrl);
var bitmap = Android.Graphics.BitmapFactory.DecodeStream(imageUrl.OpenStream());
var image = new Android.Graphics.Drawables.BitmapDrawable(bitmap);
but I don't know how to save the image or where to save it.
any help?
thanks
You're overthinking this. :-)
Once you have a Stream:
var imageUrl = new Java.Net.URL(obj.imageUrl);
System.IO.Stream stream = imageUrl.OpenStream();
you can just save it to disk:
using (var o = File.Open(
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),
"file-name"))) {
byte[] buf = new byte[1024];
int r;
while ((r = stream.Read(buf, 0, buf.Length)) > 0)
o.Write (buf, 0, r);
}
Environment.GetFolderPath(Environment.SpecialFolder.Personal) returns $APPDIR/files, which is Context.FilesDir. You don't necessarily need to use this; Context.CacheDir may be more appropriate.

Display static Google Map image in BlackBerry 5.0

I'm having a really interesting problem to solve:
I'm getting a static google map image, with an URL like this.
I've tried several methods to get this information:
Fetching the "remote resource" as a ByteArrayOutputStream, storing the Image in the SD of the Simulator, an so on... but every freaking time I get an IlegalArgumentException.
I always get a 200 http response, and the correct MIME type ("image/png"), but either way: fetching the image and converting it to a Bitmap, or storing the image in the SD and reading it later; I get the same result... the file IS always corrupt.
I really belive its an encoding problem, or the reading method (similar to this one):
public static Bitmap downloadImage(InputStream inStream){
byte[] buffer = new byte[256];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (inStream.read(buffer) != -1){
baos.write(buffer);
}
baos.flush();
baos.close();
byte[] imageData = baos.toByteArray();
Bitmap bi = Bitmap.createBitmapFromBytes(imageData, 0, imageData.length, 1);
//Bitmap bi = Bitmap.createBitmapFromBytes(imageData, 0, -1, 1);
return bi;
}
The only thing that comes to mind is the imageData.lenght (in the response, the content length is: 6005 ), but I really can't figure this one out.
Any help is more than welcome...
try this way:
InputStream input = httpConn.openInputStream();
byte[] xmlBytes = new byte[256];
int len = 0;
int size = 0;
StringBuffer raw = new StringBuffer();
while (-1 != (len = input.read(xmlBytes)))
{
raw.append(new String(xmlBytes, 0, len));
size += len;
}
value = raw.toString();
byte[] dataArray = value.getBytes();
EncodedImage bitmap;
bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
final Bitmap googleImage = bitmap.getBitmap();
Swati's answer is good. This same thing can be accomplished with many fewer lines of code:
InputStream input = httpConn.openInputStream();
byte[] dataArray = net.rim.device.api.io.IOUtilities.streamToBytes(input);
Bitmap googleImage = Bitmap.createBitmapFromBytes(dataArray, 0, -1, 1);

Resources