I have a folder in my WPF app "Images" that has several .png files with their Build Action set to Resource. These are built into my binary since I can reference them in XAML.
I would like to write these to disk in the temp folder. How do I do this?
I have found several answers referring to Embedded Resources, but not just plain resources.
Answer!
public static void ExtractFileFromResources(String filename, String location)
{
StreamResourceInfo sri = System.Windows.Application.GetResourceStream(
new Uri("pack://application:,,,/Images/" + filename));
Stream resFilestream = sri.Stream;
if (resFilestream != null)
{
BinaryReader br = new BinaryReader(resFilestream);
FileStream fs = new FileStream(location, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
byte[] ba = new byte[resFilestream.Length];
resFilestream.Read(ba, 0, ba.Length);
bw.Write(ba);
br.Close();
bw.Close();
resFilestream.Close();
}
}
Related
I'm using a Samba File Server for copy files from my Android device to a shared folder on Windows. With .txt files i haven't any problems, works fine, but I tried to copy a .jpg file into shared folder and it fails. I searched a lot of codes from internet but anyone solved my problem.
I managed to copy the image, but when I open it, is damaged.
Does anyone have any sample code?
My code is this:
Java.IO.File mfile = new Java.IO.File(item.FullName);
var mSharedFolderCalidad = new SmbFile(AppGlobalConfigSoftware.Instance.Parameters.PathToDownloadCalidad + item.Name);
//If exists don't create another time
if (!mSharedFolderCalidad.Exists())
mSharedFolderCalidad.CreateNewFile();
InputStream inFile = new FileInputStream(mfile);
SmbFileOutputStream sfos = new SmbFileOutputStream(mSharedFolderCalidad);
byte[] buf = new byte[1024];
int len;
while ((len = inFile.Read(buf)) > 0)
{
sfos.Write(buf, 0, len);
}
inFile.Close();
sfos.Close();
All help is appreciated.
Thank you.
You can use Media.Plugin from nuget to take photo firstly.
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
PhotoSize = PhotoSize.Medium,
});
public byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
MediaFile has GetStream().
You could use this to the Stream and then convert that to a byte[]. Here is one way to do that:
Define a stream
Stream imageStream;
And init it after you take the photo .
imageStream = file.GetStream();
var imageArr= ReadFully(imageStream );
And then write it to your folder .
I am doing html to pdf file . Its Downloading instantly . I dont want download instantly. i want to save the file in my project folder once converted.
My C# Code
string html ="<table><tr><td>some contents</td></tr></table>";
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=WelcomeLetter.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
StringReader sr = new StringReader(table);
Document ResultPDF = new Document(iTextSharp.text.PageSize.A4, 25, 10, 20, 30);
PdfPTable Headtable = new PdfPTable(7);
Headtable.TotalWidth = 525f;
Headtable.LockedWidth = true;
Headtable.HeaderRows = 5;
Headtable.FooterRows = 2;
Headtable.KeepTogether = true;
HTMLWorker htmlparser = new HTMLWorker(ResultPDF);
PdfWriter.GetInstance(ResultPDF, Response.OutputStream);
ResultPDF.Open();
htmlparser.Parse(sr);
ResultPDF.Close();
Response.Write(ResultPDF);
Response.End();
For saving pdf file locally in your project folder you can use FileStream class like this.
FileStream stream = new FileStream(filePath, FileMode.Create);//Here filePath is path of your project folder.
Now use this stream instead of using Response.OutputStream when you create instance of PdfWriter object.
PdfWriter.GetInstance(ResultPDF, stream);
Now do not use Responce.Write as you don't want to download your file.And close your stream at end.
stream.Close();
I'm going to combine everyone's answer into one that you should be able to drop in and use. If this works, I would accept Manish Parakhiya's answer because that had the most important part.
First, I'm going to assume you are using a recent version of iTextSharp. I think 5.5.5 is the most recent version. Second, because of this, I'm going to restructure your code a bit in order to use the using pattern. If you're stuck on an older obsolete unsupported version like 4.1.6 you'll need to re-adjust.
Almost every tutorial out there shows you that you can bind directly the Response.OutputStream. This is 100% valid but I would argue that it is also a really bad idea. Instead, bind to a more generic MemoryStream. This makes debugging much easier and your code will port and adapt that much easier.
The below code includes comments about each of the changes and what things are actually doing. The top section is all about creating a PDF from a string of HTML. The bottom actually does something with it, including writing it to disk and/or streaming it to a browser.
//Will hold our PDF eventually
Byte[] bytes;
//HTML that we want to parse
string html = "<table><tr><td>some contents</td></tr></table>";
//Create a MemoryStream to write our PDF to
using (var ms = new MemoryStream()) {
//Create our document abstraction
using (var ResultPDF = new Document(iTextSharp.text.PageSize.A4, 25, 10, 20, 30)) {
//Bind a writer to our Document abstraction and our stream
using (var writer = PdfWriter.GetInstance(ResultPDF, ms)) {
//Open the PDF for writing
ResultPDF.Open();
//Parse our HTML using the old, obsolete, not support parser
using (var sw = new StringWriter()) {
using (var hw = new HtmlTextWriter(sw)) {
using (var sr = new StringReader(html)) {
using (var htmlparser = new HTMLWorker(ResultPDF)) {
htmlparser.Parse(sr);
}
}
}
}
//Close the PDF
ResultPDF.Close();
}
}
//Grab the raw bytes of the PDF
bytes = ms.ToArray();
}
//At this point, the bytes variable holds a valid PDF file.
//You can write it disk:
System.IO.File.WriteAllBytes("your file path here", bytes);
//You can also send it to a browser:
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=WelcomeLetter.pdf");
Response.BinaryWrite(bytes);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Never do the next line, it doesn't do what you think it does and actually produces corrupt PDFs
//Response.Write(ResultPDF); //BAD!!!!!!
Response.End();
string tempDirectory = Session.SessionID.ToString();
string location = Path.Combine(Server.MapPath(
WebConfigurationManager.AppSettings["PathSet"].ToString()), tempDirectory);
if (!Directory.Exists(location))
{
Directory.CreateDirectory(location);
}
string fileName="abc.pdf";
filePath = Path.Combine(location, fileName);
I'm here for a solution to a little unresolved problem. Maybe I haven't searched for the right things as I haven't found a solution and I hope you will be able to help.
So I have a WPF application where I load an image, here I have no problems. Next I have to add some points by clicking, so i have this function:
private void ClickMouse(object sender, MouseButtonEventArgs e)
{
Point p = e.GetPosition(this);
schema.PointFromScreen(p);
var myImage3 = new Image();
var bi3 = new BitmapImage();
bi3.BeginInit();
bi3.UriSource = new Uri(_clickImagePath, UriKind.Relative);
bi3.EndInit();
myImage3.Stretch = Stretch.Fill;
myImage3.Source = bi3;
myImage3.MinWidth = 30;
myImage3.MinHeight = 30;
myImage3.Width = 30;
myImage3.Height = 30;
myImage3.Name = _pointName;
var oMargin = new Thickness(p.X, p.Y, 0, 0);
myImage3.Margin = oMargin;
mainCanva.Children.Add(myImage3);
_listImg.Add(myImage3);
PointList.Items.Add(_pointName);
}
The problem is not here but I need a context.
Now on to the main problem. I have to save the final Image to make a PDF with. I use a piece of sample code I found here (http://stackoverflow.com/questions/1824989/how-to-store-system-windows-controls-image-to-local-disk) to convert to a jpg file using ITextsharp. The only thing I have on the PDF is the first picture, so I admitted that it probably take only the first image and not the other created images on it but I really don't know how to fix it. Does some fonction exist to make a kind of screenshot of the image zone? or maybe to pay attention to all image in the zone of the principal Control.Image ?
Thank you for your help.
You should use the following code to render your Canvas as an image :
var rect = new Rect(canvas.RenderSize);
var rtb = new RenderTargetBitmap((int)rect.Right, (int)rect.Bottom, 96d, 96d, System.Windows.Media.PixelFormats.Default);
rtb.Render(canvas);
//encode as PNG
varpngEncoder = new PngBitmapEncoder();
pngEncoder.Frames.Add(BitmapFrame.Create(rtb));
//save to memory stream
using(var ms = new System.IO.MemoryStream())
{
pngEncoder.Save(ms);
System.IO.File.WriteAllBytes("logo.png", ms.ToArray());
}
(Source : Write WPF output to image file )
I have come across a couple of different ways to write images to isolated storage on some Windows Phone sites, however I am unsure which is the best to use for a camera app or if there are some that are better than others:
The first is from this post on a basic camera application: http://msdn.microsoft.com/en-us/library/hh202956(v=VS.92).aspx It takes the jpeg from the camera and writes it to isolated storage directly.
void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
string fileName = savedCounter + ".jpg";
try
{ // Write message to the UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Captured image available, saving picture.";
});
// Save picture to the library camera roll.
library.SavePictureToCameraRoll(fileName, e.ImageStream);
// Write message to the UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Picture has been saved to camera roll.";
});
// Set the position of the stream back to start
e.ImageStream.Seek(0, SeekOrigin.Begin);
// Save picture as JPEG to isolated storage.
using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
{
// Initialize the buffer for 4KB disk pages.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the image to isolated storage.
while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
// Write message to the UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Picture has been saved to isolated storage.";
});
}
finally
{
// Close image stream
e.ImageStream.Close();
}
}
It seems to use a 4kb Buffer, is there any point in doing it this way? Seems a bit more complicated than this method which converts the image to a bitmap then uses the save as Jpeg method (http://www.windowsphonegeek.com/tips/All-about-WP7-Isolated-Storage---Read-and-Save-Images):
// Create a filename for JPEG file in isolated storage.
String tempJPEG = "logo.jpg";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(tempJPEG))
{
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
StreamResourceInfo sri = null;
Uri uri = new Uri(tempJPEG, UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
If there are any alternative methods you have also I'd be interested, thanks!
Think you should check this out:
I believe I already answered this and got a +50 bounty SO Save image to Isolated Storaged using byte[]
Is there any way to access app.xaml resources of an imported XAP file (from host silverlight app) ???
Or better, import guest app.xaml into Host app.xaml
Problem is that in the imported Silverlight application, I lost all app.xaml resources, and I just see host resources... I would like to merge them...
It's possible?
I load XAP in this way
private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
var manifestStream = Application.GetResourceStream(
new StreamResourceInfo(e.Result, null),
new Uri("AppManifest.xaml", UriKind.Relative));
string appManifest = new StreamReader(manifestStream.Stream).ReadToEnd();
string assemblyName =m_rootAssembly + ".dll";
XmlReader reader = XmlReader.Create(new StringReader(appManifest));
Assembly asm = null;
while (reader.Read())
{
if (reader.IsStartElement("AssemblyPart"))
{
reader.MoveToAttribute("Source");
reader.ReadAttributeValue();
if (reader.Value == assemblyName)
{
var assemblyStream = new StreamResourceInfo(e.Result, "application/binary");
var si = Application.GetResourceStream(assemblyStream, new Uri(reader.Value, UriKind.Relative));
AssemblyPart p = new AssemblyPart();
asm = p.Load(si.Stream);
break;
}
}
}
if (asm == null)
throw new InvalidOperationException("Could not find specified assembly.");
var o = asm.CreateInstance(m_typeName);
if (o == null)
throw new InvalidOperationException("Could not create instance of requested type.");
RaiseXapLoadedEvent(o);
}
if you know the uri of the resource file, like:
"/COMPONENTNAME;component/resourcepath.xaml",
you can simply add this resource dictionary to your application by writing codes like:
Application.Current.Resources.MergedDictionaries.Add("*resourceuri*");
the "Application.Current" always points to the runtime application instance (host application), no matter where it is used.