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?
Related
I want to resize images for iOS so that I don't have to do it manually all the time. This should be done using WPF but it throws a ObjectDisposedException.
What it does is the user selects a csproj file and then an image which will be resized in 3 sizes. After resizing the file should be safed to disk but it throws an exception.
retrieving the bytes of the original BitmapImage
byte[] data = original.GetByteArray();
The used method:
public static byte[] GetByteArray(this BitmapImage bmi)
{
byte[] data;
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmi));
using (Sys.MemoryStream ms = new Sys.MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
the resizing:
private BitmapImage ResizeImage(byte[] imageData, double dheight, double dwidth)
{
int height = (int)dheight;
int width = (int)dwidth;
BitmapImage resizedImage = new BitmapImage();
using (Sys.MemoryStream ms = new Sys.MemoryStream(imageData))
{
resizedImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
resizedImage.CacheOption = BitmapCacheOption.OnLoad;
resizedImage.DecodePixelHeight = height;
resizedImage.DecodePixelWidth = width;
resizedImage.BeginInit(); // Needed only so we can call EndInit()
resizedImage.StreamSource = ms;
resizedImage.EndInit();// This does the actual loading and resizing
}
return resizedImage;
}
then the saving of the files:
public static void Save(this BitmapImage image, string filePath)
{
//PngBitmapEncoder encoder = new PngBitmapEncoder();
//encoder.Frames.Add(BitmapFrame.Create(image));
//using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
//{
// encoder.Save(fileStream);
//}
File.WriteAllBytes(filePath, image.GetByteArray());
}
how I used it:
var bmi512 = ResizeImage(data, 512, 512);
var bmi256 = ResizeImage(data, 256, 256);
var bmi128 = ResizeImage(data, 128, 128);
bmi512.Save(Sys.Path.Combine(imageFolderPath, String.Format("{0}512{1}", imageName, imageExt)));
bmi256.Save(Sys.Path.Combine(imageFolderPath, String.Format("{0}256{1}", imageName, imageExt)));
bmi128.Save(Sys.Path.Combine(imageFolderPath, String.Format("{0}128{1}", imageName, imageExt)));
it works for retrieving the byte[] of the original but when it try it for bmi512 I get the exception.
Thanks in advance
You have to call BeginInit before you set any of the BitmapImage's properties:
using (var ms = new MemoryStream(imageData))
{
resizedImage.BeginInit();
resizedImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
resizedImage.CacheOption = BitmapCacheOption.OnLoad;
resizedImage.DecodePixelHeight = height;
resizedImage.DecodePixelWidth = width;
resizedImage.StreamSource = ms;
resizedImage.EndInit();
}
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've saved an image in my DataBase in a parameter type image and I've done this with:
private void btnAceptar_Click(object sender, RoutedEventArgs e)
{
UsuariosBLL bll = new UsuariosBLL();
UsuariosBO user = new UsuariosBO();
PerfilBO perfil = cmbperf.SelectedItem as PerfilBO;
//........
user.Imagen = ConvertImageToByteArray(ruta);
bll.InsertarFilaUsuarios(user);
MessageBox.Show("Se insertó");
//.......
}
where the method ConvertToByteArray convert the image selected in a Byte Array
public byte[] ConvertImageToByteArray(string path)
{
byte[] ImageByte=null;
try
{
FileStream fs = new FileStream(path,FileMode.Open,FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageByte = br.ReadBytes((int)fs.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ImageByte;
}
and now I just wanna retrieve the image selecting a different user in my combobox.
I've tried like this:
private void cmbUsuarios_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
UsuariosBO user = e.AddedItems[0] as UsuariosBO;
//.....
MemoryStream ms = new MemoryStream(user.Imagen);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
imgFoto = img;
usuario = user;
}
But a error born:
Can not implicitly convert type 'System.Drawing.Image' to 'System.Windows.Controls.Image'
I understand what it means but I don't know how to fix it...
thanks !!
Instead of creating a System.Drawing.Image from the byte stream, you should create a WPF ImageSource and assign that to the Source property of your ImageControl.
One way to do this is by creating a BitmapImage:
using (var ms = new MemoryStream(user.Imagen))
{
var img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.StreamSource = ms;
img.EndInit();
imgFoto.Source = img;
}
Or alternatively a BitmapFrame:
using (var ms = new MemoryStream(user.Imagen))
{
imgFoto.Source = BitmapFrame.Create(ms,
BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
I am new to windows phone dev. My small app need a bytesarray from image (photo gallery). I tried many ways to convert, but it did not work fine.
here is my code:
public static byte[] ConvertBitmapImageToByteArray(BitmapImage bitmapImage)
{
using (var ms = new MemoryStream())
{
var btmMap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
// write an image into the stream
btmMap.SaveJpeg(ms, bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);
return ms.ToArray();
}
}
But then I saved this byte array to image in photogallery, I was be a black image!
public static void SavePicture2Library(byte[] bytes)
{
var library = new MediaLibrary();
var name = "image_special";
library.SavePicture(name, bytes);
}
Could anyone help me?
Please test your code :( Thanks so much!
Update resolved!
var wBitmap = new WriteableBitmap(bitmapImage);
wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
data = stream.GetBuffer();
To anyone who finds this, this works;
Image to bytes;
public static byte[] ImageToBytes(BitmapImage img)
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(img);
System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, img.PixelWidth, img.PixelHeight, 0, 100);
img = null;
return ms.ToArray();
}
}
Bytes to Image
public static BitmapImage BytesToImage(byte[] bytes)
{
BitmapImage bitmapImage = new BitmapImage();
try
{
using (MemoryStream ms = new MemoryStream(bytes))
{
bitmapImage.SetSource(ms);
return bitmapImage;
}
}
finally { bitmapImage = null; }
}
for windows phone 8
using System.IO;
public static class FileToByteArray
{
public static byte[] Convert(string pngBmpFileName)
{
System.IO.FileStream fileStream = File.OpenRead(pngBmpFileName);
using (MemoryStream memoryStream = new MemoryStream())
{
fileStream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
}
byte[] PasPhoto = FileToByteArray.Convert("Images/NicePhoto.png")
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"));