Blackberry - get image data from bitmap - image

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);

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.

When I create pdf with itextg from ListView only the same listview child appears

I am trying to create a pdf from listview items. This is my listview:
This is the result:
Below is my code:
ListView def = (ListView) findViewById(R.id.ist);
ListAdapter adapter = def.getAdapter();
int itemscount = adapter.getCount();
/*int itemsposition = adapter.getItem(position);*/
Toast.makeText(getApplicationContext(), itemscount + " temaxia", Toast.LENGTH_LONG).show();
int allitemsheight = 0;
List<Bitmap> bmps = new ArrayList<Bitmap>();
for (int i = 0; i < itemscount ; i++) {
View childView = adapter.getView(i, null, def);
/*View childView = def.getChildAt(1);*/
childView.measure(View.MeasureSpec.makeMeasureSpec(def.getWidth(),
View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
childView.layout(0, 0, childView.getMeasuredWidth(),
childView.getMeasuredHeight());
childView.setDrawingCacheEnabled(true);
childView.buildDrawingCache();
childView.getDrawingCache();
/*bmps.add(childView.getDrawingCache());
allitemsheight+=childView.getMeasuredHeight();*/
Bitmap bigbitmap = Bitmap.createBitmap(def.getMeasuredWidth(),
childView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas bigcanvas = new Canvas(bigbitmap);
def.draw(bigcanvas);
Paint paint = new Paint();
bigcanvas.drawBitmap(bigbitmap,0,childView.getMeasuredHeight(),paint);
bigbitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.scalePercent(45, 60);
myImg.setAlignment(Image.ALIGN_CENTER);
// add image to document
doc.add(myImg);
doc.add( new Paragraph());
}
I just cant find why it only gets childview in first position despite it is inside a for loop. Can anyone help me? Thanks.
I changed all the consept to: Create a big image from all childviews and then cut it to multiple pages A4 size.See below....NOTICE that first doc is never opened and never closed,but after creating image document is opened and closed properly ...............
File file = new File(dir, flname + ".pdf");
FileOutputStream fOut = new FileOutputStream(file);
FileOutputStream fOut2 = new FileOutputStream(file);
pdfWriter.getInstance(doc, fOut);
// open the document
/* doc.open();*/
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//////////////////////
ListView def = (ListView) findViewById(R.id.ist);
ListAdapter adapter = def.getAdapter();
int itemscount = adapter.getCount();
/*int itemsposition = adapter.getItem(position);*/
Toast.makeText(getApplicationContext(), itemscount + " temaxia", Toast.LENGTH_LONG).show();
View childView =null;
int allitemsheight = 0;
List<Bitmap> bmps = new ArrayList<Bitmap>();
for (int i = 0; i < itemscount ; i++) {
childView = adapter.getView(i,null,def);
/*childView = def.getChildAt(i);*/
childView.measure(View.MeasureSpec.makeMeasureSpec(def.getWidth(),
View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
childView.layout(0, 0, childView.getMeasuredWidth(),
childView.getMeasuredHeight());
childView.setDrawingCacheEnabled(true);
childView.buildDrawingCache();
/*childView.getDrawingCache();*/
bmps.add(childView.getDrawingCache());
allitemsheight+=childView.getMeasuredHeight();
}
Bitmap bigbitmap = Bitmap.createBitmap(def.getMeasuredWidth(),
allitemsheight , Bitmap.Config.ARGB_8888);
Paint paint = new Paint();
Canvas bigcanvas = new Canvas(bigbitmap);
for (int i = 0; i < bmps.size(); i++) {
Bitmap bmp = bmps.get(i);
bigcanvas.drawBitmap(bmp, 0, iHeight, paint);
/*bigcanvas.drawColor(Color.WHITE);
def.draw(bigcanvas);*/
iHeight+=bmp.getHeight();
bmp.recycle();
bmp=null;
}
bigbitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.scalePercent(45, 60);
myImg.setAlignment(Image.ALIGN_CENTER);
/*if(myImg.getWidth() >= doc.getPageSize().getWidth() || myImg.getHeight() >= doc.getPageSize().getHeight()){
myImg.scaleToFit(doc.getPageSize());
doc.newPage();
}
myImg.setAbsolutePosition((doc.getPageSize().getWidth() - myImg.getScaledWidth()) / BaseField.BORDER_WIDTH_MEDIUM, (doc.getPageSize().getHeight() - myImg.getScaledHeight()) / BaseField.BORDER_WIDTH_MEDIUM);
doc.add(myImg);
doc.add( new Paragraph());*/
///////////////////////////////////////
/////////////////////////////////////////
/////////////////////////////////////
Document document = new Document();
PdfWriter pdfWriter2 = PdfWriter.getInstance(document, fOut2);
document.open();
PdfContentByte content = pdfWriter2.getDirectContent();
myImg.scaleAbsolute(PageSize.A4);
myImg.setAbsolutePosition(0, 0);
float width = PageSize.A4.getWidth();
float heightRatio = myImg.getHeight() * width / myImg.getWidth();
int nPages = (int) (heightRatio / PageSize.A4.getHeight());
float difference = heightRatio % PageSize.A4.getHeight();
while (nPages >= 0) {
document.newPage();
content.addImage(myImg, width, 0, 0, heightRatio, 0, -((--nPages * PageSize.A4.getHeight()) + difference));
}
document.close();
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
} finally {
/*doc.close();*/
}

iTextSharp - Add image to PDF from Datatable

I try to create a PDF report from a datatable. One of the columns contents image. How can I extract the image from datatable and insert into PDF table? I'm using iTextShap version 5.4.2.0. Here is the code:
public void Report(DataTable dt, string output)
{
Document doc = new Document(PageSize.LETTER, 50, 50, 80, 50);
PdfWriter PDFWriter = PdfWriter.GetInstance(doc, new FileStream(output, FileMode.Create));
PDFWriter.ViewerPreferences = PdfWriter.PageModeUseOutlines;
iTextSharp.text.Font hel8 = FontFactory.GetFont(BaseFont.HELVETICA, 8);
doc.Open();
PdfPTable table = new PdfPTable(dt.Columns.Count);
float[] widths = new float[] { 1.2f, 1.2f, 1.2f, 1.2f, 1f, 4f, 1f, 4f };
table.SetWidths(widths);
table.WidthPercentage = 100;
PdfPCell cell = new PdfPCell(new Phrase("NewCells"));
cell.Colspan = dt.Columns.Count;
foreach (DataColumn c in dt.Columns)
{
table.AddCell(new Phrase(c.ColumnName, hel8));
}
foreach (DataRow r in dt.Rows)
{
if (dt.Rows.Count > 0)
{
table.AddCell(new Phrase(r[0].ToString(), hel8));
table.AddCell(new Phrase(r[1].ToString(), hel8));
table.AddCell(new Phrase(r[2].ToString(), hel8));
table.AddCell(new Phrase(r[3].ToString(), hel8));
table.AddCell(new Phrase(r[4].ToString(), hel8));
table.AddCell(new Phrase(r[5].ToString(), hel8));
byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
System.Drwaing.Image sdi = System.Drawing.Image.FromStream(ms);
Image img = Image.GetInstance(sdi); <-- this is the problem code
table.AddCell(img);
table.AddCell(new Phrase(r[7].ToString(), hel8));
}
}
doc.Add(table);
}
doc.Close();
}
Update: #nekno, all of your suggestions are worked.
But I still need to correct the casting at line:
byte[] byt = (byte[])r[6];
It gave me a casting exception from VS2008. So I added the conversion function (pulled it from stackoverflow):
byte[] ImageToByte(System.Drawing.Image img)
{
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
return byteArray;
}
And revised the code:
byte[] byt = ImageToByte((System.Drawing.Image)dt.Rows[e][6]);
Thanks.
What exactly is the problem? What happens when you use your problem code?
Try one of the other Image.GetInstance() overloads:
You can pass the byte array directly:
byte[] byt = (byte[])r[6];
Image img = Image.GetInstance(byt);
Or you can pass the Stream:
byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
Image img = Image.GetInstance(ms);
Or you can give iTextSharp more info about the image format:
byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
System.Drawing.Image sdi = System.Drawing.Image.FromStream(ms);
Image img = Image.GetInstance(sdi, ImageFormat.Png);
If your column can be cast to a System.Drawing.Image, then you can use it directly:
Image img = Image.GetInstance((System.Drawing.Image)r[6], System.Drawing.Imaging.ImageFormat.Png);
I have suggested steps how shows how to add image into PDF, given below code snippet show how to add logo into your PDF using iTextsharp, follow provided below steps:
I have provided link to download "itextsharp" component from given link http://sourceforge.net/projects/itextsharp/
You have to add reference into your application.
Next you have to add required namespaces "iTextsharp.text.html", "iTextsharp.text" to consume its best properties.
Now you have to add code snippet into your application given at the end, add code snippet under "button click" in code behind.
Hope it will work for you !!!
protected void btnPDF_Click(object sender, ImageClickEventArgs e)
{
DataTable dtn = new DataTable();
dtn = GetDataTable();
dtPDF = dtn.Copy();
for (int i = 0; i <= dtn.Rows.Count - 1; i++)
{
ExportToPdf(dtPDF);
}
}
public void ExportToPdf(DataTable myDataTable)
{
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);
try
{
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
Chunk c = new Chunk("" + System.Web.HttpContext.Current.Session["CompanyName"] + "", FontFactory.GetFont("Verdana", 11));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
pdfDoc.Add(p);
string clientLogo = Server.MapPath(".") + "/logo/tpglogo.jpg";
string imageFilePath = Server.MapPath(".") + "/logo/tpglogo.jpg";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
//Resize image depend upon your need
jpg.ScaleToFit(80f, 60f);
//Give space before image
jpg.SpacingBefore = 0f;
//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.HEADER;
pdfDoc.Add(jpg);
Font font8 = FontFactory.GetFont("ARIAL", 7);
DataTable dt = myDataTable;
if (dt != null)
{
//Craete instance of the pdf table and set the number of column in that table
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
PdfTable.AddCell(PdfPCell);
}
}
//PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
pdfDoc.Add(PdfTable); // add pdf table to the document
}
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
System.Web.HttpContext.Current.Response.Write(pdfDoc);
Response.Flush();
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (DocumentException de)
{
System.Web.HttpContext.Current.Response.Write(de.Message);
}
catch (IOException ioEx)
{
System.Web.HttpContext.Current.Response.Write(ioEx.Message);
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
}
}

Memory management in window phone 8

My app need to load image from web each time with provided category and it is working, the problem is memory, Image loaded in memory not being remove when next category image load and hence memory increases and the app closing with the following message-
The program '[4036] TaskHost.exe' has exited with code -2005270523 (0x887a0005).
The code is ---
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
timer.Stop();
return;
}
List rootobj = JsonConvert.DeserializeObject>(e.Result);
int c = 0, x = 0;
for (int i = 0; i < rootobj.Count; i++)
{
Image img = new Image();
img.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
img.VerticalAlignment = System.Windows.VerticalAlignment.Top;
img.Height = 160;
img.Width = 210;
img.Stretch = System.Windows.Media.Stretch.Fill;
BitmapImage bit = new BitmapImage();
string path = rootobj.ElementAt(i).ThumbnailUrl;
bit.UriSource = new Uri(path,UriKind.RelativeOrAbsolute);
img.Source = bit;
img.Margin = new Thickness(x, y, 0, 0);
c++;
if (c == 2)
{
x = 0;
y = y + 160;
c = 0;
}
else
{
x = x + 210;
}
mainGrid.Children.Add(img);
} mainGrid.Children.Add(grid);
}
and to remove i had tried these--
for (int i = 0; i < rootobj.Count; i++)
{
Image image = (Image)mainGrid.Children.ElementAt(i);
BitmapImage bitmapImage = image.Source as BitmapImage;
bitmapImage.UriSource = null;
image.Source = null;
bitmapImage = null;
image = null;
}
grid.Children.Clear();
mainGrid.Children.Remove(grid);
But it still crashes after few type of image selected.
you can do something like the following :
grid1.Children.Remove(image1);
image1 = null;

Blackberry - ListField with images from filesystem

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.

Resources