I am using the below snipped to save an audio file in the isolated storage. but the exception occurs when streamresourceinfo mapped to a absoluteUri. The uri accepts only the relative uri. Please guide me how to save the audio file using absolute Uri.
private void SaveMp3()
{
string FileName = "Audios/Deer short.mp3";
FileName = "http://www.ugunaflutes.co.uk/Deer short.mp3";
StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri(FileName, UriKind.RelativeOrAbsolute));
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(FileName))
{
myIsolatedStorage.DeleteFile(FileName);
}
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("Audio.png", FileMode.Create, myIsolatedStorage))
{
using (BinaryWriter writer = new BinaryWriter(fileStream))
{
Stream resourceStream = streamResourceInfo.Stream;
long length = resourceStream.Length;
byte[] buffer = new byte[32];
int readCount = 0;
using (BinaryReader reader = new BinaryReader(streamResourceInfo.Stream))
{
// read file in chunks in order to reduce memory consumption and increase performance
while (readCount < length)
{
int actual = reader.Read(buffer, 0, buffer.Length);
readCount += actual;
writer.Write(buffer, 0, actual);
}
}
}
}
}
}
Thanks in advance.
You can't use Application.GetResourceStream to load an external resource, because URI must to be relative to the application package http://msdn.microsoft.com/en-us/library/ms596994(v=vs.95).aspx.
You need to use WebClient.OpenReadAsync to download your mp3 file and after save it locally to IsolatedStorage, peace of example:
var webClient = new WebClient();
webClient.OpenReadCompleted += (sender, args) =>
{
if (args.Error != null)
{
//save file here
}
};
webClient.OpenReadAsync(new Uri("http://www.ugunaflutes.co.uk/Deer short.mp3"));
Related
I'm currently working on a project that requires importing the image drawn on a WPF Canvas (Mostly Geometries like lines and ellipses inside Path) into a Word Document. I'm using Openxml to do the job. Here's what I did
I convert read the content of the Canvas into a memory stream
I used the guide provided my Microsoft on how to insert image into Word files How to: Insert a picture into a word processing document (Open XML SDK)
Here's what I've got so far,
Canvas is converted into memory stream by the following piece of code
public static Stream CreateJPGStream(this Canvas canvas)
{
RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)canvas.ActualWidth, (int)canvas.ActualHeight, 96d, 96d, PixelFormats.Pbgra32);
canvas.Measure(new Size((int)canvas.ActualWidth, (int)canvas.ActualHeight));
canvas.Arrange(new Rect(new Size((int)canvas.ActualWidth, (int)canvas.ActualHeight)));
renderBitmap.Render(canvas);
var stream = new MemoryStream();
var encoder = new JpgBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
encoder.Save(stream);
return stream;
}
I believe this was not the cause of the problem since I have been using this code for a while now and I haven't had any issues so far
Then I just modified code from Microsoft Guide
public static void InsertPicture(this WordprocessingDocument word, Stream stream)
{
MainDocumentPart mainPart = word.MainDocumentPart;
if (mainPart == null)
{
mainPart = word.AddMainDocumentPart();
mainPart.Document = new Document() { Body = new Body() };
}
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
imagePart.FeedData(stream);
AddImageToBody(word, mainPart.GetIdOfPart(imagePart));
}
private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
{
var element =
new Drawing(
new DW.Inline(
new DW.Extent() { Cx = 990000L, Cy = 792000L },
new DW.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 0L,
BottomEdge = 0L
},
new DW.DocProperties()
{
Id = 1U,
Name = "Picture 1"
},
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks() { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = (UInt32Value)0U,
Name = "New Bitmap Image.jpg"
},
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri =
"{28A0092B-C50C-407E-A947-70E740481C1C}"
})
)
{
Embed = relationshipId,
CompressionState =
A.BlipCompressionValues.Print
},
new A.Stretch(
new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = 990000L, Cy = 792000L }),
new A.PresetGeometry(
new A.AdjustValueList()
)
{ Preset = A.ShapeTypeValues.Rectangle }))
)
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{
DistanceFromTop = 0U,
DistanceFromBottom = 0U,
DistanceFromLeft = 0U,
DistanceFromRight = 0U,
EditId = "50D07946"
});
wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
}
Now to join this two methods together
public void InsertPicture(Canvas c)
{
using (var word = OpenXmlHelper.Create(filePath))
{
var stream = c.CreateJPGStream();
word.InsertPicture(stream);
}
}
But when I open the document, I get this
Am I doing something wrong with the memorysteam or on the openxml side? Can someone enlighten me please.
PS: I have looked at similar questions already like Inserting Image into DocX using OpenXML and setting the size
After writing to a stream, the stream's position will be at the end of the stream. You must rewind the stream to the beginning before you read from it.
stream.Position = 0;
or
stream.Seek(0, System.IO.SeekOrigin.Begin);
Direct to the point: I want to download and save a .pdf file so that the user can see it later in the Media Library.
I'm looking for a way to achieve this in Windows Phone 8 Silverlight.
Here is the code I'm using right now:
private void DownloadPDF(string url)
{
var client = new WebClient();
client.OpenReadCompleted += client_OpenReadCompleted;
this.FileName = Path.GetFileName(url);
client.OpenReadAsync(new Uri(url));
}
async void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
// Save file:
var buffer = new byte[e.Result.Length];
await e.Result.ReadAsync(buffer, 0, buffer.Length);
using (var storageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = storageFile.OpenFile(this.FileName, FileMode.Create))
{
await stream.WriteAsync(buffer, 0, buffer.Length);
}
}
// Open file:
var local = ApplicationData.Current.LocalFolder;
var pdffile = await local.GetFileAsync(this.FileName);
Windows.System.Launcher.LaunchFileAsync(pdffile);
var progressIndicator = new ProgressIndicator()
{
IsVisible = false
};
SystemTray.SetProgressIndicator(this, progressIndicator);
}
Thank you very much!
I have saved the files to database. These files may be of type Doc, PDF or Image. Now I'm trying to open these files from a DataGridView Cell_Click event using this code.
private void dgvDocuments_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dgvDocuments.Columns[0].Index)
{
int id =Convert.ToInt32(dgvDocuments.Rows[e.RowIndex].Cells[1].Value);
string query = "SELECT Photo FROM [dbo].[tblHR_Emloyee_Documents] WHERE ID = " + id;
Utility.Generate_Window_Control.databaseFileRead(query);
}
}
public static MemoryStream databaseFileRead(string query)
{
MemoryStream memoryStream = new MemoryStream();
using (var varConnection = new SqlConnection(Utility.Global_Connection.conn))
using (var sqlQuery = new SqlCommand(query, varConnection))
{
varConnection.Open();
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null)
{
sqlQueryResult.Read();
var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
//using (var fs = new MemoryStream(memoryStream, FileMode.Create, FileAccess.Write)) {
memoryStream.Write(blob, 0, blob.Length);
//}
}
}
return memoryStream;
}
During debug it shows me no error. Values are correct. But It is not opening the files. Kindly guide me how can I do this?
I have a utility that allows the user to take a camera photo and upload it, in addition to another option to upload a file. I've got most of it working, except for the part where I have to convert the webcam image to a jpg prior to upload. The code below has no error but produces invalid image data:
void CaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e)
{
busyIndicator.IsBusy = true;
stopCapture();
capturedImage.ImageSource = e.Result;
ImageTools.ExtendedImage eimg = e.Result.ToImage();
var encoder = new ImageTools.IO.Jpeg.JpegEncoder();
Stream stream = eimg.ToStreamByExtension("jpg");
//DO THIS LATER
//if (stream.Length > 512000)
//{
// eimg = ExtendedImage.Resize(eimg, 240, new NearestNeighborResizer());
// stream = eimg.ToStreamByExtension("jpg");
//}
encoder.Encode(eimg, stream);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(stream);
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
// picture file a class object to be used by uploader
pictureFile.PictureName = "webcam.jpg"; // name will be changed later
pictureFile.PictureStream = bytes;
HtmlPage.Window.Invoke("gotDetails_WebCam", ""); // post page, then come back and do upload
}
Here is what PictureFile looks like:
[DataContract]
public class PictureFile
{
[DataMember]
public string PictureName { get; set; }
[DataMember]
public byte[] PictureStream { get; set; }
}
Can anyone figure out what I'm doing wrong to produce the bytes needed for a jpeg?
good to see that you solved,
here is my running code,
I use png format,there is also file size check.
Maybe it helps s.one else.
dSrvPR is my Domain Service Class instance
photo is an entity object in my EF.
_captureSource.CaptureImageCompleted += ((s, args) =>
{
if (dSrvPR.PR_PATIENTPHOTOs.Count > 0 && photo != null)
{
dSrvPR.PR_PATIENTPHOTOs.Remove(photo);
}
dSrvPR.PR_PATIENTPHOTOs.Clear();
photo = new PR_PATIENTPHOTO();
ImageTools.ExtendedImage eimg=args.Result.ToImage();
var encoder=new ImageTools.IO.Png.PngEncoder();
Stream stream= eimg.ToStreamByExtension("png");
if (stream.Length > 512000)
{
eimg= ExtendedImage.Resize(eimg, 240, new NearestNeighborResizer());
stream = eimg.ToStreamByExtension("png");
}
if (stream.Length <= 512001)
{
BinaryReader binary = new BinaryReader(stream);
//Read bytes from the BinaryReader and put them into a byte array.
Byte[] file = binary.ReadBytes((int)stream.Length);
photo.ID = Guid.NewGuid();
photo.PHOTO = file;
photo.PHOTODATE = DateTime.Now;
photo.ISACTIVE = true;
//some more unrelated fields
dSrvPR.PR_PATIENTPHOTOs.Add(photo);
dSrvPR.SubmitChanges();
//Msg succedded
}
else
{
Util.alert(...,"file size exceeded! :)";
}
});
My mistake. It seems I had some extra code in there (unnecessarily converting stream to bitmap). Here is what I got working:
void CaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e)
{
busyIndicator.IsBusy = true;
stopCapture();
capturedImage.ImageSource = e.Result;
ImageTools.ExtendedImage eimg = e.Result.ToImage();
var encoder = new ImageTools.IO.Jpeg.JpegEncoder();
Stream stream = eimg.ToStreamByExtension("jpg");
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
// picture file a class object to be used by uploader
pictureFile.PictureName = "webcam.jpg"; // name will be changed later
pictureFile.PictureStream = bytes;
HtmlPage.Window.Invoke("gotDetails_WebCam", ""); // post page, then come back and do upload
}
I just want to get a BitmapImage from a internet URL, but my function doesn't seem to work properly, it only return me a small part of the image. I know WebResponse is working async and that's certainly why I have this problem, but how can I do it synchronously?
internal static BitmapImage GetImageFromUrl(string url)
{
Uri urlUri = new Uri(url);
WebRequest webRequest = WebRequest.CreateDefault(urlUri);
webRequest.ContentType = "image/jpeg";
WebResponse webResponse = webRequest.GetResponse();
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = webResponse.GetResponseStream();
image.EndInit();
return image;
}
First you should just download the image, and store it locally in a temporary file or in a MemoryStream. And then create the BitmapImage object from it.
You can download the image for example like this:
Uri urlUri = new Uri(url);
var request = WebRequest.CreateDefault(urlUri);
byte[] buffer = new byte[4096];
using (var target = new FileStream(targetFileName, FileMode.Create, FileAccess.Write))
{
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
target.Write(buffer, 0, read);
}
}
}
}
Why not use System.Net.WebClient.DownloadFile?
string url = #"http://www.google.ru/images/srpr/logo3w.png";
string file = System.IO.Path.GetFileName(url);
System.Net.WebClient cln = new System.Net.WebClient();
cln.DownloadFile(url,file);
this is the code i use to grab an image from a url....
// get a stream of the image from the webclient
using ( Stream stream = webClient.OpenRead( imgeUri ) )
{
// make a new bmp using the stream
using ( Bitmap bitmap = new Bitmap( stream ) )
{
//flush and close the stream
stream.Flush( );
stream.Close( );
// write the bmp out to disk
bitmap.Save( saveto );
}
}
The simpliest is
Uri pictureUri = new Uri(pictureUrl);
BitmapImage image = new BitmapImage(pictureUri);
you can then change BitmapCacheOption to start the retrieval process. However, image is retrieved in async. But you shouldn't care much