Background task (writablebitmap) will be terminated in windows phone - c#

I'm updating my app for windows phone 8.1 and I want to create a transparent live tile. I'm using The ToolStack PNG library for creating png images and it works fine in first look !
I am using the code below in background task
private void CreateWideTile()
{
int width = 691;
int height = 336;
string imagename = "WideBackground";
WriteableBitmap b = new WriteableBitmap(width, height);
var canvas = new Grid();
canvas.Width = b.PixelWidth;
canvas.Height = b.PixelHeight;
var textBlock = new TextBlock();
textBlock.Text = "example text...";
textBlock.Margin = new Thickness(10, 55, 0, 0);
textBlock.Width = 140;
textBlock.Foreground = new SolidColorBrush(Colors.White);
textBlock.FontSize = 30;
canvas.Children.Add(textBlock);
b.Render(canvas, null);
b.Invalidate();
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists("/Shared/ShellContent/" + imagename + ".png"))
store.DeleteFile("/Shared/ShellContent/" + imagename + ".png");
var stream = store.OpenFile("/Shared/ShellContent/" + imagename + ".png", FileMode.OpenOrCreate);
b.WritePNG(stream);
stream.Close();
}
}
private void CreateMediumTile()
{
int width = 336;
int height = 336;
string imagename = "MediumBackground";
WriteableBitmap b = new WriteableBitmap(width, height);
var canvas = new Grid();
canvas.Width = b.PixelWidth;
canvas.Height = b.PixelHeight;
var textBlock = new TextBlock();
textBlock.Text = "example text...";
textBlock.Margin = new Thickness(10, 55, 0, 0);
textBlock.Width = 140;
textBlock.Foreground = new SolidColorBrush(Colors.White);
textBlock.FontSize = 30;
canvas.Children.Add(textBlock);
b.Render(canvas, null);
b.Invalidate();
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists("/Shared/ShellContent/" + imagename + ".png"))
store.DeleteFile("/Shared/ShellContent/" + imagename + ".png");
var stream = store.OpenFile("/Shared/ShellContent/" + imagename + ".png", FileMode.OpenOrCreate);
b.WritePNG(stream);
stream.Close();
}
}
private void CreateSmallTile()
{
int width = 159;
int height = 159;
string imagename = "SmallBackground";
WriteableBitmap b = new WriteableBitmap(width, height);
var canvas = new Grid();
canvas.Width = b.PixelWidth;
canvas.Height = b.PixelHeight;
var textBlock = new TextBlock();
textBlock.Text = "example text...";
textBlock.Margin = new Thickness(10, 55, 0, 0);
textBlock.Width = 140;
textBlock.Foreground = new SolidColorBrush(Colors.White);
textBlock.FontSize = 30;
canvas.Children.Add(textBlock);
b.Render(canvas, null);
b.Invalidate();
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists("/Shared/ShellContent/" + imagename + ".png"))
store.DeleteFile("/Shared/ShellContent/" + imagename + ".png");
var stream = store.OpenFile("/Shared/ShellContent/" + imagename + ".png", FileMode.OpenOrCreate);
b.WritePNG(stream);
stream.Close();
}
}
as I mentioned, this code works fine but after 5 times run, the background task will be terminated and won't run anymore...I'm really confused. I've searched all the internet and I just guess the problem is because of memory leak. but I don't know how to solve this confusing problem.
I also used GC.Collect(); but it didn't help at all.
please please give some advice

I also use the ToolStack to generate the transparent live tile in WP8.1, but use the method ExtendedImage.WriteToStream().

Related

Filestream with Bitmap

Ok now, the current code i am using
{
using (fs = new FileStream("test", FileMode.Create))
{
byte[] b = new byte[iLength + 1];
int y1 = 0;
axCZKEM1.GetPhotoByName(MachineNo, photoPath + ".jpg", out b[0], out y1);
btImage = b;
if (btImage != null)
{
fs.Write(btImage, 0, btImage.Length);
}
if (fs.Length > 0)
{
bmp1 = new Bitmap(fs);
bmp1.Save(ImgPath + photoPath + ".jpg");
Console.WriteLine(photoPath);
// fs = null;
bmp1 = new Bitmap(fs);
When i use the above code in backgroundworker or in thread ( bmp1 = new Bitmap(fs); ) this line is throwing Parameter is not valid exception , if somebody can help me out on this please.

Hide an Image in itextsharp

What I am trying to achieve is to hide the image (either by opacity or transparency) using itextsharp. So far the image is being show as below:
string webURL = "X:/XXXXXX/web.png";
iTextSharp.text.Image webIcon = iTextSharp.text.Image.GetInstance(webURL);
webIcon.Annotation = new Annotation(0,0,0,0, "http://www.xxxxx.com");
webIcon.ScaleAbsolute(35f, 35f);
webIcon.SetAbsolutePosition(227,23);
webIcon.Transparency = new int[] {0,0 };
//state.FillOpacity = 0.2f;
//webIcon.GrayFill = 0.2f;
doc.Add(webIcon);
How do I change the transparency so the image's visibility is null?
You need to use PdfGState. In your case:
var writer = PdfWriter.GetInstance(document, output);
document.Open();
string webURL = "http://www.apache.org/foundation/press/kit/feather.png";
Image webIcon = Image.GetInstance(webURL);
webIcon.Annotation = new Annotation(0, 0, 0, 0, "http://www.google.com");
webIcon.ScaleAbsolute(35f, 35f);
webIcon.SetAbsolutePosition(227, 23);
PdfContentByte canvas = writer.DirectContentUnder;
canvas.SaveState();
PdfGState state = new PdfGState();
state.FillOpacity = 0.6f; // THIS is where you set opacity
canvas.SetGState(state);
canvas.AddImage(webIcon);
canvas.RestoreState();
document.Close();
Hope it helps

It is possible to cut an image of ItextSharp.Text.Image?

I'm creating a pdf file from an large image, but my image is too large, and it does not fit in the only page. then i need split this image to create more pages.
any idea?
public FileResult ResultadoParaPdf(string file)
{
string fileStringReplace = file.Replace("data:image/png;base64,", "");
var image = Convert.FromBase64String(fileStringReplace);
const int HorizontalMargin = 40;
const int VerticalMargin = 40;
using (var outputMemoryStream = new MemoryStream())
{
using (var pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin))
{
iTextSharp.text.pdf.PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);
pdfWriter.CloseStream = false;
pdfDocument.Open();
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
Image img = Image.GetInstance(image);
img.WidthPercentage = 100;
PdfPCell c = new PdfPCell(img, true);
c.Border = PdfPCell.NO_BORDER;
c.Padding = 5;
c.Image.ScaleToFit(750f, 750f);
table.AddCell(c);
pdfDocument.Add(table);
pdfDocument.Close();
byte[] created = outputMemoryStream.ToArray();
outputMemoryStream.Write(created, 0, created.Length);
outputMemoryStream.Position = 0;
return File(created, "application/pdf", "teste.pdf");
}
}
}

Add absolute position text to pdf in memorystream

I need to add text to the lower right corner of a pdf. I was able to successfully do this with an annotation but I couldn't flatten it so I attempted to add the text via a paragraph instead. Now none of my text is showing up. Could anyone point out where I'm going wrong with my code below? (Or maybe just tell me how to flatten an annotation... the commented out portion works fine I just need it flattened)
private MemoryStream AddPageNumbers(MemoryStream stream)
{
MemoryStream ms = new MemoryStream();
PdfStamper Stamper = null;
PdfReader Reader = new PdfReader(stream);
try
{
PdfCopyFields Copier = new PdfCopyFields(ms);
Copier.AddDocument(Reader);
Copier.Close();
PdfReader docReader = new PdfReader(ms.ToArray());
ms = new MemoryStream();
Stamper = new PdfStamper(docReader, ms);
for (int i = 1; i <= Reader.NumberOfPages; i++)
{
//iTextSharp.text.Rectangle newRectangle = new iTextSharp.text.Rectangle(315, 19, 560, 33);
//var pcb = new iTextSharp.text.pdf.PdfContentByte(Stamper.Writer);
//string PageNumber = "Confirmation of Completion Report " + i.ToString() + " of " + Reader.NumberOfPages.ToString();
//FontFactory.RegisterDirectories();
//Font fontNormalArial = new Font(FontFactory.GetFont("Arial", 8f, Font.NORMAL));
//Paragraph para = new Paragraph(PageNumber, fontNormalArial);
//var annot = iTextSharp.text.pdf.PdfAnnotation.CreateFreeText(Stamper.Writer, newRectangle, para.Content, pcb);
//annot.Flags = iTextSharp.text.pdf.PdfAnnotation.FLAGS_PRINT;
//annot.BorderStyle = new iTextSharp.text.pdf.PdfBorderDictionary(0, 0);
//Stamper.AddAnnotation(annot, i);
//Stamper.FreeTextFlattening = true;
//Stamper.FormFlattening = true;
PdfContentByte cb = new PdfContentByte(Stamper.Writer);
string PageNumber = "Confirmation of Completion Report " + i.ToString() + " of " + Reader.NumberOfPages.ToString();
FontFactory.RegisterDirectories();
Font fontNormalArial = new Font(FontFactory.GetFont("Arial", 10, Font.NORMAL));
Paragraph para = new Paragraph(PageNumber, fontNormalArial);
para.Alignment = Element.ALIGN_RIGHT;
ColumnText ct = new ColumnText(cb);
ct.AddText(para);
ct.SetSimpleColumn(315, 19, 560 , 38);
ct.SetIndent(316, false);
ct.Go();
}
}
catch (Exception ex)
{
string querystring = "?error=" + ex.Message.ToString();
Response.Redirect("~/ErrorPage.aspx" + querystring);
}
finally
{
if (Stamper != null)
{
Stamper.Close();
}
}
return ms;
}

HttpHandler issue, Retrieving image

The following HttpHandler is to retrieve image from database. When I initially tested it it was working fine. but now the problem is that it still retieve image but does not display it in image control that is in Listview.
`public void ProcessRequest (HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
using (SqlConnection connection = ConnectionManager.GetConnection())
{
SqlCommand command = new SqlCommand("select Normal_Thumbs from User_Images where Id=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
if (dr[0] != DBNull.Value)
{
Stream str = new MemoryStream((Byte[])dr[0]);
Bitmap Photo = new Bitmap(str);
int Width = Photo.Width;
int Height = Photo.Height;
int imagesize = 200;
if (Photo.Width > Photo.Height)
{
Width = imagesize;
Height = Photo.Height * imagesize / Photo.Width;
}
else
{
Width = Photo.Width * imagesize / Photo.Height;
Height = imagesize;
}
Bitmap bmpOut = new Bitmap(150, 150);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, Width, Height);
g.DrawImage(Photo, 0, 0, Width, Height);
MemoryStream ms = new MemoryStream();
bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] bmpBytes = ms.GetBuffer();
bmpOut.Dispose();
ms.Close();
context.Response.Write(bmpBytes);
context.Response.End();
}
}
}
The Handler Retrieves the image but the listview does not display it.
Try this approach, setting content type to the response.
...
context.Response.Clear();
context.Response.ContentType = System.Drawing.Imaging.ImageFormat.Png.ToString();
context.Response.OutputStream.Write(bmpBytes, 0, bmpBytes.Length);
context.Response.End();
...
Regards.

Categories

Resources