Loading a PNG image in HTML file - windows-phone-7

In my Windows Phone7.1 App Iam loading a HTML file from local path in a WebBrowser. For this I
converted a PNG Image to base64 format using the below code and the problem is base 64 format of image path is not loading the image in the webbrowser.
Please help me where i made mistake?
string s = "data:image/jpg;base64,";
imgStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NewUIChanges.Htmlfile.round1.png");
byte[] data = new byte[(int)imgStream.Length];
int offset = 0;
while (offset < data.Length)
{
int bytesRead = imgStream.Read(data, offset, data.Length - offset);
if (bytesRead <= 0)
{
throw new EndOfStreamException("Stream wasn't as long as it claimed");
}
offset += bytesRead;
}
base64 = Convert.ToBase64String(data);
Stream htmlStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NewUIChanges.Htmlfile.equity_built.html");
StreamReader reader = new StreamReader(htmlStream);
string htmlcontent = reader.ReadToEnd();
htmlcontent = htmlcontent.Replace("round1.png", s + base64);
wb.NavigateToString(htmlcontent);

If you have no error, that data contains your image, and round1.png exist in htmlcontent, then it's just probably a image type error, try this:
string s = "data:image/png;base64,";

Related

Issue viewing image created using iTextSharp

I have been successful in creating image from PDF using iTextSharp. It creates images equal to number of pages in PDF but generated images does not preview in any image viewer software. It says image is corrupted. Below is the code I have created.
try
{
PdfReader reader = null;
int currentPage = 1;
int pageCount = 0;
string destinationFolderPath = string.Format(#"{0}PageImages\{1}", BaseDataPath, Convert.ToString(documentId));
if (!Directory.Exists(destinationFolderPath))
{
Directory.CreateDirectory(destinationFolderPath);
}
reader = new PdfReader(filePath);
reader.RemoveUnusedObjects();
pageCount = reader.NumberOfPages;
string ext = ".png";
for (int i = 1; i <= pageCount; i++)
{
PdfReader reader1 = new PdfReader(filePath);
string destinationFilePath = string.Format(#"{0}/{1}{2}", destinationFolderPath, Convert.ToString(i), ext);
reader1.RemoveUnusedObjects();
Document doc = new Document(reader1.GetPageSizeWithRotation(currentPage));
PdfCopy pdfCpy = new PdfCopy(doc, new FileStream(destinationFilePath, FileMode.Create));
doc.Open();
for (int j = 1; j <= 1; j++)
{
PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage);
//pdfCpy.SetFullCompression();
pdfCpy.AddPage(page);
currentPage += 1;
}
doc.Close();
pdfCpy.Close();
reader1.Close();
reader.Close();
}
}
catch (Exception ex)
{
throw ex;
}
Could someone please suggest what is wrong here?
Thanks
You are creating a PDF file using PdfCopy, but you are storing that PDF as if you were creating a PNG file:
string ext = ".png";
string destinationFilePath =
string.Format(#"{0}/{1}{2}",
destinationFolderPath, Convert.ToString(i), ext);
PdfCopy pdfCpy = new PdfCopy(doc,
new FileStream(destinationFilePath, FileMode.Create));
You can't open a .png file in a PDF viewer. Your operating system will try to open the file you're creating as if it were an image, but the bytes of that "image" will be PDF bytes and your image viewer won't recognize it.
Change this line:
string ext = ".png";
To this:
string ext = ".pdf";
And you'll be able to open your file in a PDF viewer.
By the way: your code is awkward. For instance. I don't understand why you'd create a look to execute something only once:
for (int j = 1; j <= 1; j++)
Also: if it's your intention to convert PDF pages to PNG, reconsider. iTextSharp doesn't convert PDF to images.

OutOfMemoryException when Inserting larger images in SQL Server CE

Inserting smaller images work fine. However, when the image file gets bigger than about 2MB, I get an OutOfMemoryException.
I tried with SqlCeUpdatableRecord and a parameterized SqlCeCommand. Using the SqlCeCommand, the exception is raised at ExecuteNonQuery().
With SqlCeUpdatableRecord, the exception is raised at SqlCeUpdatableRecord.SetBytes().
I’ve tried increasing buffer size and temp file size without it seeming to have an effect. I've debugged with GetTotalMemory and there seems to be plenty of resources available.
Any tips would be highly appreciated.
The SQL Server CE database is synchronized with a main SQL Server database and handling images as separate files would introduce a truckload of other issues. The solution has worked fine for years as most WM handhelds only capture images at 5MP or less. However, newer models with support for 8MP images is causing issues.
Here is a simplified version of the SqlCeUpdateblRecord implementation:
System.Data.SqlServerCe.SqlCeUpdatableRecord newRecord = base.CreateRecord();
newRecord["ImageId"] = ImageId;
newRecord["ImageType"] = ImageType;
//64kb buffer (Have tested with different buffer sizes (up to 8MB)
newRecord.SetBytesFromFile("ImageFull", ImageFullFileName, 65536);
newRecord["ImageThumb"] = ImageThumb;
newRecord["ImageDate"] = ImageDate;
base.Insert(newRecord);
.....
public static void SetBytesFromFile(this SqlCeUpdatableRecord obj, string name, string filename, int buffersize)
{
int _column = obj.GetOrdinal(name);
byte[] buffer = new byte[buffersize];
int bytesread;
long offset = 0;
using (FileStream fs = new FileStream(filename,FileMode.Open))
{
bytesread = fs.Read(buffer, 0, buffersize);
while (bytesread > 0)
{
//This will raise OutOfMemoryException for imagefiles larger than appx. 2mb, regardless of buffersize
obj.SetBytes(_column, offset, buffer, 0, bytesread);
offset = offset + (long)bytesread;
bytesread = fs.Read(buffer, 0, buffersize);
}
}
}
Here is a simplified version of the paramterized query:
using (var cmdInsert = new SqlCeCommand("INSERT INTO [Image_CF] ( [ImageId], [ImageType], [ImageFull], [ImageThumb], [ImageDate]) VALUES " +
" ( #ImageId, #ImageType, #ImageFull, #ImageThumb, #ImageDate)"))
{
cmdInsert.Connection = Database.IrisPdaConnection;
cmdInsert.Parameters.Add("#ImageId", System.Data.SqlDbType.Int).Value = ImageId;
cmdInsert.Parameters.Add("#ImageType", System.Data.SqlDbType.NVarChar).Value = ImageType;
cmdInsert.Parameters.Add("#ImageFull", System.Data.SqlDbType.Image).Value = GetFileAsBytes(ImageFullFileName);
cmdInsert.Parameters.Add("#ImageThumb", System.Data.SqlDbType.Image).Value = ImageThumb;
cmdInsert.Parameters.Add("#ImageDate", System.Data.SqlDbType.NVarChar).Value = ImageDate;
// OutOfMemoryException for images larger than appx. 2MB
cmdInsert.ExecuteNonQuery();
}
public byte[] GetFileAsBytes(string filename)
{
FileStream fs;
byte[] result;
using (fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
// a byte array to read the image
result = new byte[fs.Length];
fs.Read(result, 0, System.Convert.ToInt32(fs.Length));
}
return result;
}

image stream to base64 string in WP7

in my wp7 application i am selecting image from media library and i want to get base64 string of that image because i am sending it to my wcf service to create image on server. the code for getting base64 string is as follows:
void taskToChoosePhoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
fileName = e.OriginalFileName;
selectedPhoto = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
imgSelected.Source = selectedPhoto;
int[] p = selectedPhoto.Pixels;
int len = p.Length * 4;
result = new byte[len]; // ARGB
Buffer.BlockCopy(p, 0, result, 0, len);
base64 = System.Convert.ToBase64String(result);
}
}
but at server this code creates image file but in the format is invalid. I cross validated the base64 string but i think app is giving wrong base64string what could be the reason please help to find out the problem.
You are sending base64-encoded pixels on the server. I'm not sure that this is what you need. How about converting Stream to the base64 string?
var memoryStream = new MemoryStream();
e.ChosenPhoto.CopyTo(memoryStream);
byte[] result = memoryStream.ToArray();
base64 = System.Convert.ToBase64String(result);

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

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