How to save bitmapimage in Isolated storage? - silverlight

I am developing silverlight web part by using the client object model. I am getting the bitmap image from sharepoint server. Now I want to save this bitmap image in isolated storage. So I am using following code
WriteableBitmap wb = new WriteableBitmap(attachments);
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream("abcd1.jpg", FileMode.Create, isoFile))
{
using (StreamWriter sw = new StreamWriter(isoStream))
{
sw.Write(wb.ToByteArray());
}
}
}
Now I am seeing the saved image at location C:\Users\Rent2\AppData\LocalLow\Microsoft\Silverlight\is\vzvpufsm.s4i\m0laonzr.til\1\s\nkhajster01es5wdoyfxd0n5rd2dls3ovyu4wcdig04zjx44hyaaafea\f
When I click on it, it gives me message as "Invalid Image". Can you please tell me how should i write code so that I can see the actual image after saving it in isolated storage ?

private void zipFile()
{
context = Microsoft.SharePoint.Client.ClientContext.Current;
Microsoft.SharePoint.Client.File.OpenBinaryDirect(
context,
#"/TemplateInvoice/" + App.templateFileName + ".xlsx", successFile, FailFile);
}
private void successFile(object sender, OpenBinarySucceededEventArgs args)
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Obtain the isolated storage for an application.
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
Stream strm = args.Stream;
using (var isoStream = store.OpenFile(App.templateFileName + ".zip", FileMode.OpenOrCreate))
{
// Read the resource file into a byte array.
bytes = new byte[strm.Length];
int numBytesToRead = (int)strm.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = strm.Read(bytes, numBytesRead, numBytesToRead);
// The end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
numBytesToRead = bytes.Length;
// Write the byte array to the IsolatedStorageFileStream.
isoStream.Write(bytes, 0, numBytesToRead);
//isoStream.Dispose();
}
strm.Close();
string path = App.templateFileName + ".zip";
ZipHelp.UnZip(path, System.IO.Path.GetDirectoryName(path), 4096);
replaceFileContent();
string rootDirectory = System.Windows.Browser.HttpUtility.UrlDecode(path);
string fileName = ZipHelp.Zip(rootDirectory.Replace(".zip", ""), invoice);
//string filename = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + "Invoice1.xlsx";
// Read the resource file into a byte array.
using (var stream = store.OpenFile(fileName, FileMode.Open))
{
bytes = new byte[stream.Length];
int numBytesToRead = (int)stream.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = stream.Read(bytes, numBytesRead, numBytesToRead);
// The end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
InvoiceTemplete invoiceTemplate = new InvoiceTemplete(fileName, bytes, SetMessage);
invoiceTemplate.AddDocument(invoiceTemplate);
}
}
//mark rows as billed
foreach (var item in PrivatePayList)
{
MedwaiverViewModel MedwaiverViewModelObj = new MedwaiverViewModel();
MedwaiverViewModelObj.ChangeBillingStatus(item.ListItemId, "Billed");
if (MedwaiverTimeLogList != null)
{
MedwaiverTimeLogList.Remove(item);
}
if (ClientSpecificTimeLogList != null)
{
ClientSpecificTimeLogList.Remove(item);
}
if (rangeBoundTimeLogListForDate != null)
{
rangeBoundTimeLogListForDate.Remove(item);
}
if (vRangeBoundTimeLogListForDateAndClient != null)
{
vRangeBoundTimeLogListForDateAndClient.Remove(item);
}
}
}
catch (IsolatedStorageException isx)
{
MessageBox.Show(isx.Message);
}
});
}
private void FailFile(object sender, OpenBinaryFailedEventArgs e)
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Fail");
});
}
//The following class zip and unzip the file
class ZipHelp
{
static List<string> folderPathList = new List<string>();
public static string Zip(string rootDirectory, string fileName)
{
byte[] buffer;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream zipFileStream = store.CreateFile(fileName + ".xlsx");
ZipOutputStream zipOutStream = new ZipOutputStream(zipFileStream);
zipOutStream.UseZip64 = UseZip64.Off;
//zipOutStream.CanPatchEntries
foreach (var item in folderPathList)
{
string entryName = "";
buffer = new byte[4096];
if (item.Substring(0,1) == #"/")
{
//removes leading /
entryName = item.Substring(1);
}
else
{
entryName = item;
}
ZipEntry entry = new ZipEntry(entryName);
//entry.CompressionMethod = CompressionMethod.Deflated;
//entry.
entry.IsZip64Forced();
//entry.IsDirectory
zipOutStream.PutNextEntry(entry);
using (IsolatedStorageFileStream stream = store.OpenFile(rootDirectory + #"\" + item, FileMode.Open))
{
int size;
do
{
size = stream.Read(buffer, 0, buffer.Length);
zipOutStream.Write(buffer, 0, size);
} while (size > 0);
stream.Close();
}
}
zipOutStream.Close();
zipFileStream.Close();
}
return fileName + ".xlsx";
//string[] directories = GetLocationTypes();
//zip();
//string[] filenames = Directory.GetFiles(directories);
//using (var store = IsolatedStorageFile.GetUserStoreForApplication())
//{
// using (var isoStream = store.OpenFile("#" + rootDirectory, FileMode.OpenOrCreate))
// {
// //foreach(string dir in
// }
//}
}
private static string[] GetLocationTypes()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
return store.GetDirectoryNames();
}
}
/// <summary>
/// UnZip a file
/// </summary>
/// <param name="SrcFile">source file path</param>
/// <param name="DstFile">unzipped file path</param>
/// <param name="BufferSize">buffer to use</param>
public static void UnZip(string SrcFile, string DstFile, int BufferSize)
{
folderPathList.Clear();
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
FileStream fileStreamIn = store.OpenFile(SrcFile, FileMode.Open, FileAccess.Read);
ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
string rootDirectory = System.Windows.Browser.HttpUtility.UrlDecode(SrcFile);
rootDirectory = rootDirectory.Replace(".zip", "");
store.CreateDirectory(rootDirectory);
while (true)
{
ZipEntry entry = zipInStream.GetNextEntry();
if (entry == null)
break;
if (entry.Name.Contains("/"))
{
string[] folders = entry.Name.Split('/');
string lastElement = folders[folders.Length - 1];
var folderList = new List<string>(folders);
folderList.RemoveAt(folders.Length - 1);
folders = folderList.ToArray();
string folderPath = "";
foreach (string str in folders)
{
folderPath = folderPath + "/" + str;
if (!store.DirectoryExists(rootDirectory + "/" + folderPath))
{
store.CreateDirectory(rootDirectory + "/" + folderPath);
}
}
folderPath = folderPath + "/" + lastElement;
writeToFile(BufferSize, fileStreamIn, zipInStream, rootDirectory, folderPath);
}
else
{
writeToFile(BufferSize, fileStreamIn, zipInStream, rootDirectory, entry.Name);
}
}
zipInStream.Close();
fileStreamIn.Close();
}
private static void writeToFile(int BufferSize, FileStream fileStreamIn, ZipInputStream zipInStream, string rootDirectory, string folderPath)
{
IsolatedStorageFile store1 = IsolatedStorageFile.GetUserStoreForApplication();
FileStream fileStreamOut = store1.OpenFile(rootDirectory + "/" + folderPath, FileMode.Create, FileAccess.Write);
folderPathList.Add(folderPath);
int size;
byte[] buffer = new byte[BufferSize];
do
{
size = zipInStream.Read(buffer, 0, buffer.Length);
fileStreamOut.Write(buffer, 0, size);
} while (size > 0);
fileStreamOut.Close();
}
}

I can think of two viable options here.
In your code above, save off the Pixels array of the WriteableBitmap. Then to restore it, you would create a WriteableBitmap of the appropriate size and the set the Pixels array to the stored data.
-or-
Use a HttpWebRequest or WebClient request to get the raw image stream and save that to IsolatedStorage.
There are pros and cons to each of these, in the first case the data is uncompressed and will take up more space in isolated storage and you would not be able to open the image from disk outside of Silverlight, similar to the issue you had above. For the second option you can run into cross domain issues if the images are on a different server than your Silverlight XAP file and it's also a bit more complex to implement.

The basic problem is that you're storing the decoded RGBA pixels array as a JPEG file - but they're not the same. Your code is basically correct: you just can't use this method to store it as a JPEG file. But if you happen to know that the image is, say, 800x600, you could create an 800x600 WriteableBitmap, and then set the Pixels property to the retrieved stream's byte array. Or if you don't know the dimensions when you're retrieving it, you could store the dimensions as the first two integers in the stream (before you write the pixels to the stream), and read out the dimensions when you're reading the file. You'd effectively be creating your own very simplistic .bmp format.

Related

Optimizing Replacing Bytes of Some File in Java 8

I have this method in Java and I want to improve it.
The method is used to replace some part (at the beginning, in the middle or at the end) of some File with the new bytes (the selected part can be replaced by less or more bytes).
The selection is done, by position(start) and quantity.
I can't to use external libraries (guava, or some other).
Here my old code:
public static void replaceBytesFile(RandomAccessFile rafTarget,
byte[] replacers, int start, int quantity) {
//replaces exact amount of bytes of a file starting at a specified position
RandomAccessFile rafTemp = null;
//Ini Select a Random NonExistent File
File userDirectory = new File(System.getProperty("user.dir"));
File temporalFile;
boolean existsTemporalFile = false;
String temporalFilename = "";
while (!existsTemporalFile) {
temporalFilename = "File_" + Double.toString(100000 * Math.random()) + ".tmp";
temporalFilename = userDirectory + MethodGen.FS + temporalFilename;
temporalFile = new File(temporalFilename);
if (!temporalFile.exists()) {
existsTemporalFile = true;
}
}
//End Select a Random NonExistent File
try {
rafTemp = new RandomAccessFile(temporalFilename, "rw");
int workBufferSize = 65536;
//Ini Copy first (Start - 1) MethodBytes
int step = workBufferSize;
int countPosition = 0;
while (countPosition < start) {
rafTarget.seek(countPosition);
rafTemp.seek(countPosition);
if ((start - countPosition) < step) {
step = start - countPosition;
}
byte[] WorkBuffer = new byte[step];
rafTarget.read(WorkBuffer);
rafTemp.write(WorkBuffer);
countPosition += step;
}
//End Copy first (start - 1) MethodBytes
rafTemp.write(replacers);
rafTarget.seek(start + quantity);
int end = (int) rafTarget.length();
//Ini Copy last MethodBytes
step = workBufferSize;
countPosition = start + quantity;
while (countPosition < end) {
rafTarget.seek(countPosition);
rafTemp.seek(countPosition - quantity + replacers.length);
if ((end - countPosition) <= step) {
step = end - countPosition;
}
byte[] WorkBuffer = new byte[step];
rafTarget.read(WorkBuffer);
rafTemp.write(WorkBuffer);
countPosition += step;
}
//End Copy last MethodBytes
rafTarget.setLength(0);
step = workBufferSize;
countPosition = 0;
end = (int) rafTemp.length();
//Ini Copy all MethodBytes to original
while (countPosition < end) {
rafTemp.seek(countPosition);
rafTarget.seek(countPosition);
if ((end - countPosition) <= step) {
step = end - countPosition;
}
byte[] WorkBuffer = new byte[step];
rafTemp.read(WorkBuffer);
rafTarget.write(WorkBuffer);
countPosition += step;
}
//End Copy all MethodBytes to original
rafTemp.close();
temporalFile = new File(temporalFilename);
temporalFile.delete();
} catch (IOException ioe) {
System.out.println(ioe.toString());
} finally {
try {
if (rafTemp != null) {
rafTemp.close();
}
} catch (IOException e) {
}
}
}
I'm copying manually in from original file to temporal file where the changes are performed, later ,
My code is working, but I want to know some best alternative in Java 8 (preferred).
Now How is test?
public static void main(String[] args) {
String originalFilename = "OriginalTraveling.txt";
String copiedFilename = "TravelingToBeChanged.txt";
Path copiedPath = Paths.get(copiedFilename);
Path originalPath = new File(originalFilename).toPath();
System.out.println("filename:" + originalFilename);
String contet = "I want to travel to my Country.";
try {
RandomAccessFile raf = new RandomAccessFile(originalFilename, "rw");
putBytesFile(raf, contet.getBytes(), 0);
Files.copy(originalPath, copiedPath, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e) {
System.out.println("Exception caught " + e.toString());
}
try {
RandomAccessFile raf = new RandomAccessFile(copiedFilename, "rw");
String toBeChanged = "my Country.";
String toBeInserted = "India, China, Europe, Latin America, Australia.";
int position = contet.indexOf(toBeChanged);
replaceBytesFile(raf, toBeInserted.getBytes(), position, toBeChanged.length());
}
catch (IOException e) {
System.out.println("Exception caught " + e.toString());
}
try {
RandomAccessFile raf = new RandomAccessFile(copiedFilename, "rw");
String replacedContent = new String(getBytesFile(raf, 0, (int) raf.length()));
String toBeChanged = "Latin America";
String toBeInserted = "Colombia";
int position = replacedContent.indexOf(toBeChanged);
replaceBytesFile(raf, toBeInserted.getBytes(), position, toBeChanged.length());
} catch (IOException e) {
System.out.println("Exception caught " + e.toString());
}
}
Method to put Bytes!
public static void putBytesFile(RandomAccessFile RAFTarget, byte[] content, int position) {
int size = content.length;
try {
long oldPosition = RAFTarget.getFilePointer();
if (!((position < 0) || !(size > 0))) {
RAFTarget.seek(position);
RAFTarget.write(content);
RAFTarget.seek(oldPosition);
}
} catch (java.io.IOException e) {
System.out.println(e.toString());
}
}
Method Get Files!
public static byte[] getBytesFile(RandomAccessFile RAFSource, int position, int quantity) {
byte[] content = null;
try {
long oldPosition = RAFSource.getFilePointer();
if ((position < 0) || !(quantity > 0)) {
return (content);
} else {
if (RAFSource.length() < (position + quantity)) {
quantity = (int) RAFSource.length() - position;
}
RAFSource.seek(position);
content = new byte[quantity];
RAFSource.read(content);
RAFSource.seek(oldPosition);
}
} catch (java.io.IOException e) {
System.out.println(e.toString());
}
return content;
}
Content of OriginalTraveling.txt
I want to travel to my Country.
Content of TravelingToBeChanged.txt
I want to travel to India, China, Europe, Latin America, Australia.
Finally the Content of TravelingToBeChanged.txt
I want to travel to India, China, Europe, Colombia, Australia.
If it can be noticed, they are NOT changed by the same number of bytes.
Do you know some alternative to replace contents of File?
Even for ancient code, this looks unnecessary complicated.
E.g. instead of
//Ini Select a Random NonExistent File
File userDirectory = new File(System.getProperty("user.dir"));
File temporalFile;
boolean existsTemporalFile = false;
String temporalFilename = "";
while (!existsTemporalFile) {
temporalFilename = "File_" + Double.toString(100000 * Math.random()) + ".tmp";
temporalFilename = userDirectory + MethodGen.FS + temporalFilename;
temporalFile = new File(temporalFilename);
if (!temporalFile.exists()) {
existsTemporalFile = true;
}
}
just use
File temporalFile = File.createTempFile("File_", ".tmp", userDirectory);
See createTempFile
Further, instead of
int step = workBufferSize;
int countPosition = 0;
while (countPosition < start) {
rafTarget.seek(countPosition);
rafTemp.seek(countPosition);
if ((start - countPosition) < step) {
step = start - countPosition;
}
byte[] WorkBuffer = new byte[step];
rafTarget.read(WorkBuffer);
rafTemp.write(WorkBuffer);
countPosition += step;
}
Use
for(int step=workBufferSize, countPosition=0; countPosition < start; countPosition += step){
rafTarget.seek(countPosition);
rafTemp.seek(countPosition);
if ((start - countPosition) < step) {
step = start - countPosition;
}
byte[] WorkBuffer = new byte[step];
rafTarget.read(WorkBuffer);
rafTemp.write(WorkBuffer);
}
As you clearly have an initial statement, a condition and an increment operation, in other words, a typical for loop. The same applies to the other two while loops.
However, with newer APIs, things are much simpler anyway:
// consider using long for position and Path for the file, unless
// the RandomAccessFile is really needed for other purposes
public static void replaceBytesFile(RandomAccessFile rafTarget,
byte[] replacers, int start, int quantity) throws IOException {
// no need to force a particular directory for the temp file
Path tmp = Files.createTempFile("File_", ".tmp");
// use import static java.nio.file.StandardOpenOption.*;
// try( ... ) closes automatically, perfect for a temp file with DELETE_ON_CLOSE
try(FileChannel tmpCh = FileChannel.open(tmp, READ, WRITE, DELETE_ON_CLOSE)) {
// closing the target channel would also close rafTarget RandomAccessFile
FileChannel target = rafTarget.getChannel();
// just keep the data before start position, only copy remainder
long retainStart = start + (long)quantity, toCopy = target.size() - retainStart;
target.transferTo(retainStart, toCopy, tmpCh);
// write the replacement
target.write(ByteBuffer.wrap(replacers), start);
// copy back the remainder, to the new position
tmpCh.position(0);
target.transferFrom(tmpCh, start + (long)replacers.length, toCopy);
// adapt the length if necessary
target.truncate(start + toCopy + replacers.length);
}
}

Displaying image from database in iTextSharp document [duplicate]

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

C# Windows Application Image Resizing Before Saving

I have this Code to Save a Pic to my Solution Explorer Images Folder.
private void btnUploadImage_Click(object sender, EventArgs e)
{
//The String used to store the location of the file that is currently loaded in the picture box picFile
String location;
//The String used to store the name of the file that is currently loaded in the picture box picFile
String fileName;
ofdImageUpload.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
//Showing the fileopen dialog box
ofdImageUpload.ShowDialog();
//showing the image opened in the picturebox
imgCapture.Image = new Bitmap(ofdImageUpload.FileName);
//storing the location of the pic in variable
location = ofdImageUpload.FileName;
txtImgLocation.Text = location;
//storing the filename of the pic in variable
fileName = ofdImageUpload.SafeFileName;
//pictureboxImage.Image.Save();
imgCapture.SizeMode = PictureBoxSizeMode.StretchImage;
if (imgCapture.Image != null)
{
lblHiddenMsg.Text = "";
}
}
private void InsertGatepassEntry(int RowId)
{
string ContName = txtContName.Text.Trim();
string ContAdd = richtxtContAddress.Text.Trim();
string VisitorName = txtEmpName.Text.Trim();
string VisitorAdd = txtEmpAddress.Text.Trim();
string VisitorFathersName = txtEmpFatherName.Text.Trim();
string VisitorAge = txtEmpAge.Text.Trim();
string VisitorEsi = txtEsi.Text.Trim();
string VisitorContact = txtEmpContactNo.Text.Trim();
string VisitorBloodGrp = comboxBloodGroup.SelectedText.Trim();
string VisitorIssueDate = dtpEmpDateOfIssue.Text.Trim();
string imagename = ofdImageUpload.SafeFileName;
if (imagename != null || imagename != "") //Check If image is Selected from Computer's Hard Drive
{
if (imgCapture.Image != null)
{
//string imagepath = ofdImageUpload.FileName;
//string picname = imagepath.Substring(imagepath.LastIndexOf('\\'));
string picname = imagename;
string path = Application.StartupPath.Substring(0, Application.StartupPath.LastIndexOf("bin"));
Bitmap imgImage = new Bitmap(imgCapture.Image); //Create an object of Bitmap class/
//string fullPathName = path + "Images" + picname;
imgImage.Save(path + "Images\\" + txtEmpName.Text + txtEsi.Text + ".jpg");
string Image = "Images\\" + txtEmpName.Text + txtEsi.Text + ".jpg";
string GatepassNo = LoadLastGatepassNo();
switch (Contractor.InsertGatepassEntry(RowId, ContName, ContAdd, VisitorName, VisitorAdd, VisitorFathersName, VisitorAge, VisitorEsi, VisitorContact, VisitorBloodGrp, VisitorIssueDate, Image, GatepassNo))
{
case ProjectCreateStatus.Insertrow:
lblMessage.Text = "Information inserted successfully!";
lblMessage.ForeColor = System.Drawing.Color.Green;
lblGatepassNo.Text = GatepassNo;
break;
}
}
else
{
lblHiddenMsg.Visible = true;
lblHiddenMsg.Text = "Please capture or browse an image First";
}
}
else //image is directly uploding from Webcam Capture
{
string Image = lblHiddenMsg.Text;
string GatepassNo = LoadLastGatepassNo();
switch (Contractor.InsertGatepassEntry(RowId, ContName, ContAdd, VisitorName, VisitorAdd, VisitorFathersName, VisitorAge, VisitorEsi, VisitorContact, VisitorBloodGrp, VisitorIssueDate, Image, GatepassNo))
{
case ProjectCreateStatus.Insertrow:
lblMessage.Text = "Information inserted successfully!";
lblMessage.ForeColor = System.Drawing.Color.Green;
lblGatepassNo.Text = GatepassNo;
break;
}
}
}
private void bntCapture_Click(object sender, EventArgs e)
{
imgCapture.Image = imgVideo.Image;
Bitmap b = new Bitmap(imgCapture.Image);
string path = Application.StartupPath.Substring(0, Application.StartupPath.LastIndexOf("bin"));
b.Save(path + "Images\\" + txtEmpName.Text + txtEsi.Text + ".jpg");
lblHiddenMsg.Text = path + "Images\\" + txtEmpName.Text + txtEsi.Text + ".jpg";
}
Now I want to Save those uploaded Pic to my Images Folder to a particular Size like 250x250. can Anyone Help ? m new in Windows Application C#.
To resize your image use:
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
yourImage = resizeImage(yourImage, new Size(250,250));
hi you can add the "Size" class as a parameter of your Bitmap constructor to resize the image
i did for you this function to make it easy hope that will help you
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
yourImage = resizeImage(yourImage, new Size(250,250));

How to accelerate loading resource file in J2ME

I'm writing a J2ME application using J2ME Wireless Toolkit 2.2
I have the following code:
public class BusReader
{
private String[] fileNames;
private final String allFilesInfoFile = "files_in_dir";
public BusReader ()
{
fileNames = getFileNames ();
String busNo = getBusNo ("BusNo1p.bin");
}
public String[] getAllBusFiles ()
{
return fileNames;
}
public String getBusNo (String fileName)
{
String[] fileLines = loadResourceFile (fileName);
int linesCount = fileLines.length;
for (int i=0;i<linesCount;++i)
if (fileLines[i].equals ("[BusNo]") && i < linesCount-1)
return fileLines[i+1];
return null;
}
public String getDefaultDirection (String fileName)
{
String[] fileLines = loadResourceFile (fileName);
int linesCount = fileLines.length;
for (int i=0;i<linesCount;++i)
if (fileLines[i].equals ("[BusDirection]") && i < linesCount-1)
return fileLines[i+1];
return null;
}
private String[] getFileNames ()
{
return loadResourceFile (allFilesInfoFile);
}
private String[] loadResourceFile (String fileName)
{
String content = "";
try
{
Reader in = new InputStreamReader(this.getClass().getResourceAsStream(fileName), "iso-8859-2");
StringBuffer temp = new StringBuffer(1024);
char[] buffer = new char[1024];
int read;
while ((read=in.read(buffer, 0, buffer.length)) != -1)
temp.append(buffer, 0, read);
content = temp.toString();
} catch (IOException e) {
return null;
}
int len = content.length ();
if (content.charAt (len-1) == '\n' && content.charAt (len-2) == '\r')
{
String newContent = "";
for (int i=0;i<len-2;++i)
newContent += content.charAt (i);
content = newContent;
}
String[] fileLines = TString.Split ("\r\n", new TString(content));
for (int i=0;i<fileLines.length; ++i)
{
fileLines[i] = fileLines[i].trim ();
if (fileLines[i].length () == 0)
fileLines[i] = "";
}
return fileLines;
}
}
All works correctly, but the problem is when I'm trying to copy my application into mobile phone. On my mobile phone when I open the application before application show I must wait 35 seconds. This is because, constructor executes the function twice:
loadResourceFile (String fileName)
which loads the resource file. Files size which function is loading are: 1.22KB and 29KB.
The question is: How to accelerate loading function (loadResourceFile)?
I tried to create java class files as resource data but it exceeded java memory limit. I changed arrays String[][][][] to String[][][] and it was loading on my mobile phone in 15 seconds. I thought when I will load data as a resource it will work faster. My mobile phone: Nokia 3110c
I found it.
It was following lines (it takes 35 seconds):
if (content.charAt (len-1) == '\n' && content.charAt (len-2) == '\r')
{
String newContent = "";
for (int i=0;i<len-2;++i)
newContent += content.charAt (i);
content = newContent;
}

Out of memory exception in WP7

When I am trying to save some images to my IsolatedStorage there is an Out of Memory exception occures. If the image count is more than 20 this error occurs. I am downloading all these images and save them in a temp folder in isolated storage. When I am trying to save these images from temp folder to a folder named myImages in isolated storage, this error occurs. Each photo is read from temp and write to myImages one by one. When some 20 or 25 photos are saved to myImages then this error occures. Images has an average size of 350-400 KB. How can I avoid this error?
My Code is :
private void SaveImages(int imageCount)
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
BitmapImage bitmap;
string tempfoldername = "Temp";
string tempfilename = string.Empty;
string folderName = "myImages";
string imageName = string.Empty;
for (int i = 0; i < imageCount; i++)
{
tempfilename = tempfoldername + "\\" + (i + 1) + ".jpg";
bitmap = GetImage(tempfoldername, tempfilename);
imageName = folderName + "\\" + (i + 1) + ".jpg";
SaveImage(bitmap, imageName, folderName);
if (isf.FileExists(imageName))
isf.DeleteFile(imageName);
bitmap = null;
}
}
private BitmapImage GetImage(string foldername, string imageName)
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isfs;
BitmapImage bi = new BitmapImage();
MemoryStream ms = new MemoryStream();
byte[] data;
int FileSize = 0;
if (isf.DirectoryExists(foldername))
{
isfs = isf.OpenFile(imageName, FileMode.Open, FileAccess.Read);
data = new byte[isfs.Length];
isfs.Read(data, 0, data.Length);
ms.Write(data, 0, data.Length);
FileSize = data.Length;
isfs.Close();
isfs.Dispose();
bi.SetSource(ms);
ms.Dispose();
ms.Close();
return bi;
}
return null;
}
private void SaveImage(BitmapImage bitmap, string imageName, string folderName)
{
int orientation = 0;
int quality = 100;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isf.DirectoryExists(folderName))
isf.CreateDirectory(folderName);
if (isf.FileExists(imageName))
isf.DeleteFile(imageName);
Stream fileStream = isf.CreateFile(imageName);
WriteableBitmap wb = new WriteableBitmap(bi);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, orientation, quality);
fileStream.Close();
}
}
how can I fix this error?
Your BitmapImage is most likely leaking the memory.
Be sure to set the UriSource to null so that the memory is freed.
Have a look at http://blogs.msdn.com/b/swick/archive/2011/04/07/image-tips-for-windows-phone-7.aspx for more.

Resources