I'm having some really weird problems trying to load a file pragmatically into my project to save to a local folder.
I can load the file fine in my .xaml code, as so:
<BitmapImage x:Key="Image" UriSource ="/Assets/Submandibular_oedema.jpg" />
And I can display that image on my page. However, when I try to load the image and use it in my xaml.cs code like this
uriMyFile = new Uri("/Assets/Submandibular_oedema.jpg", UriKind.RelativeOrAbsolute);
It cannot find the file and as a result, won't let me do anything with the URI.
For background, my aim is to get the image stream then save it to a local folder.
I know it'll be a stupid little problem, but I can't find any solutions to it.
Thanks!
Try full path (specify your project assembly)
uriMyFile = new Uri("/YourAssemblyName;component/Assets/Submandibular_oedema.jpg",UriKind.RelativeOrAbsolute);
Update after Starktastics comment:
I finally understood your problem: you need the Application.GetResourceStream method to retrieve a stream of your resource, read from that stream and write it to a file stream.
var streamResourceInfo = Application.GetResourceStream(uri);
var stream = streamResourceInfo.Stream;
var byteBuffer = new byte[stream.Length];
using (stream)
{
stream.Read(byteBuffer, 0, byteBuffer.Length);
}
using (var fileStream = new FileStream("photo.jpg", FileMode.Create))
{
fileStream.Write(byteBuffer, 0, byteBuffer.Length);
}
I've updated the solution that you can download here.
Original answer:
If you use a WPF application, make sure that the asset you added to your project is to Build Action 'Resource'. You can check that in the properties pane after you clicked the file.
In any case, your syntax for the URI is correct. I checked it in a small project myself and it works. You can download it here (DropBox link)
Feel free to leave a comment.
Try to use
uriMyFile=new Uri("ms-appx:///Assets/YourImage.png"));
This works for me while trying to show a diffrent map icon for each place.
Related
I am trying download an image from a website and put it in a picturebox.
// response contains HttpWebResponse of the page where the image is
using (Stream inputStream = response.GetResponseStream()) {
using (Stream outputStream = File.Open(fileName, FileMode.Create)) {
byte[] buffer = new byte[4096];
int bytesRead;
do {
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
response.Close();
After that, the downloaded image is assigned to a PictureBox like such:
if (imageDownloaded) {
pictureBox1.Image = Image.FromFile(filePath);
}
This all works like a charm first time, but the second time I run the code I get System.IO.IOException: "Additional information: The process cannot access the file ...(file path) ... because it is being used by another process.". I have no idea why...
I looked at 4 other threads such as this one, but they were basically stressing out the need to close streams, which I do, so none of them helped me.
Before you recommend to use pictureBox1.Load() I can't because I need the image downloaded for further development.
EDIT 1: I have actually tried to dispose the image by putting pictureBox1.Image = null before the code above is executed. It is still giving me an exception.
The Image.FromFile docs state:
The file remains locked until the Image is disposed.
So you need to dispose your Image too to be able to overwrite the file.
Try using the Clone method on your image and dispose the original Image.
The thing is related to the Image.FromFile. If we read a documentation, there is a note:
The file remains locked until the Image is disposed.
This pretty much explains the behavior you get.
To resolve this, you might need to create a copy of the image and assign it to a PictureBox .
From MSDN:
The file remains locked until the Image is disposed.
This means its the PictureBox that is holding the file open.
You have two options:
Dispose of the PictureBox image before writing the new file.
Download the file, make a copy of it and load the copy into the PictureBox - this allows you to write over the downloaded file freely.
I'll be the contrarian here. :)
While cloning/copying the image will resolve the exception, it raises a different question: why are you overwriting to the same file for a new image?
It seems to me that a better approach would be to download subsequent files to different file names (if they are really different files), or to simply reuse the file already downloaded instead of hitting the network again (if it's just a new request for the same file).
Even if you want to repeatedly download the same file (perhaps you expect the actual file contents to change), you can still download to a new name (e.g. append a number to the file name, use a GUID for the local file name, etc.)
i am trying to make a simple application in which i have an image i have copied it in Assets folder of my project. The image i got from the web, and it is in the png format.
can some body give me an idea that how i can copy my images to my project so that when i deploy the project on device i will able to load them.
Current i what i am trying is.
var streamResource = App.GetResourceStream(new Uri("/Assets/Tiles/gradiant-mask.png", UriKind.Relative));
using (Stream stream = streamResource.Stream) {
var maskData = new byte[stream.Length];
stream.Read(maskData, 0, maskData.Length);
}
But i always get the streamResource object as null and the may be the reason is it didn't find the file on the device. can some body guide me that how i can load the image on the device in my wp8 application.
Make sure the Build action is set to Content on the properties of the image file in Visual Studio.
If you want the Build action to be set to Resource, use the following URI syntax:
new Uri("/YOUR_PROJECT_NAME;component/Assets/Tiles/gradiant-mask.png", UriKind.Relative)
Using the Content build action is recommended.
you can directly load image by :
in XAML
Source="/Assets/Tiles/gradiant-mask.png"
or in code behind by
imagename.Source = new Uri("/Assets/Tiles/gradiant-mask.png",UriKind.Relative);
set the build action as content .
I am having a really weird issue with my image saving method. First, here is the method:
public static void uploadImageToServer(string savePath, HttpPostedFile imageToUpload, bool overwrite)
{
byte[] myData = new Byte[imageToUpload.ContentLength];
imageToUpload.InputStream.Read(myData, 0, imageToUpload.ContentLength);
FileStream newFile = new FileStream(savePath, FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();
}
As you can see from the input parameters this method works in conjuction with the FileUpload control. Now I am using this method from two pages which both have a FileUpload control. On one page the image uploads file, on the other page it results in a corrupted file.
I am really at a loss as to why the image is being corrupted. I am using the same image, the same method, and the same input control.
Is there any way I can debug this?
Gonna steal alexn's answer <_<
You are over-complicating it. Just use the built-in FileUpload::SaveAs(save_path) that is provided for you.
You can use the Server.MapPath() method to help you get a dynamic path to your root directory, go from there and append the file name to it.
Not sure why you are getting that error. My best guess is either your savePath is broken (or the filename/extension appended to it), or the bytes are not being read/written to perfectly.. Anyway, you should not get that error by using the method I described (considering you don't mess up the file extension :).
I'm trying to build a wp7 application that must allow user to read ebooks in epub format. Since there isn't any available library to read epub file on a windows phone, I'm trying to create one. So I must unzip the file and then parse it.
The problem is that I can't unzip the epub file. I'm using SharpZipLib.WindowsPhone7.dll but I get an exception:
Attempt to access the method failed: System.IO.File.OpenRead(System.String)
on this line:
ZipInputStream s = new ZipInputStream(File.OpenRead(path_epubfile));
Can any one help me, please?
It's going to depend on how the content is obtained. There's three possible options here;
Option 1: If the content is added to your project with a Build Action of "Content" you can obtain a stream by using the StreamResourceInfo class (In the System.Windows.Resources namespace)
StreamResourceInfo info = Application.GetResourceStream(new Uri("MyContent.txt", UriKind.Relative));
using (info.Stream) {
// Make use of the stream as you will
}
Option 2: If you've added it to your project and set the Build Action to "Embedded Resource" then you'll need to use GetManifestResourceStream()
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ProjectName.MyContent.txt")) {
// Make use of stream as you will
}
Note: You'll need to replace "ProjectName" with the name of your project. So if your project was "EPubReader" and the embedded resource was "Example.txt" you'd need to pass "EPubReader.Example.txt" to GetManifestResourceStream(). You can use GetManifestResourceNames() to see what resources are available.
Option 3: If you've obtained the content at run time, it'll be stored in IsolatedStorage.
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
using (IsolatedStorageFileStream stream = store.OpenFile("MyContent.txt", FileMode.Open)) {
// Make use of stream as you will
}
}
Greetings all,
Thanks for reading and sharing any insights. I've created a new simple Windows Phone 7 application. I have two Image objects on the form I would like to update with various .png files. I have included the .png files into my project, and I believe I am building proper URi resources pointing to these files.
Uri myImage1URi = new Uri( strImage1, UriKind.RelativeOrAbsolute );
Uri myImage2URi = new Uri( strImage2, UriKind.RelativeOrAbsolute );
System.Windows.Media.Imaging.BitmapImage bi1 = new System.Windows.Media.Imaging.BitmapImage(myImage1URi);
System.Windows.Media.Imaging.BitmapImage bi2 = new System.Windows.Media.Imaging.BitmapImage(myImage2URi);
image1.Source = bi1;
image1.Stretch = Stretch.Fill;
image2.Source = bi2;
image2.Stretch = Stretch.Fill;
This alone is not accomplishing what I want (to update the images to the two from the URi's).
I know there is something a bit off going on (IE: I am doing something dumb) in that all of the BitmapImage class descriptions mention that I have to do a .BeginInit() before I work with the BitmapImage object, and a .EndInit() call afterwards. These method calls don't work for me, so I know something is amiss....
Or maybe I am competely off base and I simply need a way to tell my main window to repaint itself? That thought has occurred to me as well.
Thanks again.
The following will load an image that is in the appropriate path and is set as having a build action content.
myImg.Source = new BitmapImage(new Uri("/images/filename.png", UriKind.Relative));
It assumes XAML on the page like:
<Image x:Name="myImg" />
This seems very similar to what you're doing. Simplify what you're doing ot get it working.
Does it work with just using one image?
Is the path in strImageN a valid path?
Do the image files have their build action set to Content?