after selecting image display same image inside picturebox - c#

on buttonclick I'm taking image from file system and save into database, everything is ok but I want when I select image to display that image into pictureBox1
OpenFileDialog open = new OpenFileDialog() { Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg" };
if (open.ShowDialog() == DialogResult.OK)
{
txtPhoto.Text = open.FileName;
}
string image = txtPhoto.Text;
Bitmap bmp = new Bitmap(image);
FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
byte[] bimage = new byte[fs.Length];
fs.Read(bimage, 0, Convert.ToInt32(fs.Length));
fs.Close();
byte[] Photo = bimage;

You can use Image property to set the Image for PictureBox Control.
Try This:
DialogResult result= openFileDialog1.ShowDialog();
if(result==DialogResult.OK)
pictureBox1.Image =new Bitmap(openFileDialog1.FileName);
if you want to add it in your code
Complete Code:
OpenFileDialog open = new OpenFileDialog() { Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg" };
if (open.ShowDialog() == DialogResult.OK)
{
txtPhoto.Text = open.FileName;
}
string image = txtPhoto.Text;
Bitmap bmp = new Bitmap(image);
pictureBox1.Image = bmp;//add this line
FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
byte[] bimage = new byte[fs.Length];
fs.Read(bimage, 0, Convert.ToInt32(fs.Length));
fs.Close();
byte[] Photo = bimage;

Simple code:
picturebox.Image = Bitmap.FromFile(yourimagepath);

OpenFileDialog open = new OpenFileDialog()
{
Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg"
};
if (open.ShowDialog() == DialogResult.OK)
{
PictureBoxObjectName.Image = Image.FromFile(open.FileName);
}

openFileDialog1.Multiselect = false;
openFileDialog1.Filter= "jpg files (*.jpg)|*.jpg";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
foreach (String file in openFileDialog1.FileNames)
{
picturebox1.Image = Image.FromFile(File);
}
}
This is for selection of one image.

Related

Copy a file but with a "Save as" window

I just want to copy a file to another location. But with a FileDialog.
I tried the code below but this is not working as I want...
Is there any other solution ?
SaveFileDialog saveFile = new SaveFileDialog();
if (saveFile.ShowDialog() == DialogResult.OK)
{
string newDirectory = saveFile.FileName;
System.IO.File.Copy(Path, newDirectory);
}
EDIT :
I want something like this :
Word exemple
A Filedialog with the default name of my source file and the right type. You can see an example when you try to save a Word.
Use the FileStream class . Which is more flexible, especially if you want to track the data transfer process byte by byte.
SaveFileDialog saveFile = new SaveFileDialog();
if (saveFile.ShowDialog() == DialogResult.OK)
{
string newDirectory = saveFile.FileName;
byte[] buffer = new byte[1024 * 1024];
int currentBlockSize = 0;
using (source = new FileStream(Path, FileMode.Open, FileAccess.Read))
{
using (dest = new FileStream(newDirectory, FileMode.CreateNew, FileAccess.Write))
{
while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, currentBlockSize);
}
}
}
}

Cannot read a Bitmap image that I just saved in Base64

I try to load a picture (PNG), save-it in Base64 in a text file and reload it, but I only see gliberish pictures (black and white, very ugly, far from original!) after I load the picture from the text file.
Where's my problem?
BTW all examples (load the picture from image file, save to base64, load from base64) are all taken from SO questions.
First it's how a load the pictures from the PNG file:
try
{
var openFileDialog = new OpenFileDialog
{
CheckFileExists = true,
Multiselect = false,
DefaultExt = "png",
InitialDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)
};
if (openFileDialog.ShowDialog() == true)
{
Bitmap img;
using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
img = new Bitmap(stream);
}
Logo.Source = BitmapToImageSource(img);
}
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString(), "An error occured", MessageBoxButton.OK, MessageBoxImage.Warning);
}
Save it to base64:
try
{
Bitmap img = BitmapSourceToBitmap2((BitmapSource) Logo.Source);
string base64String;
using (var stream = new MemoryStream())
{
img.Save(stream, ImageFormat.Png);
byte[] imageBytes = stream.ToArray();
base64String = Convert.ToBase64String(imageBytes);
}
string fileName = string.Format(CultureInfo.InvariantCulture, "image{0:yyyyMMddHHmmss}.txt",
DateTime.Now);
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName);
using (var stream = File.Open(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
using (var writer = new StreamWriter(stream, System.Text.Encoding.UTF8))
{
writer.Write(base64String);
writer.Flush();
}
}
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString(), "An error occured", MessageBoxButton.OK, MessageBoxImage.Warning);
}
BitmapSourceToBitmap2:
int width = srs.PixelWidth;
int height = srs.PixelHeight;
int stride = width*((srs.Format.BitsPerPixel + 7)/8);
IntPtr ptr = IntPtr.Zero;
try
{
ptr = Marshal.AllocHGlobal(height*stride);
srs.CopyPixels(new Int32Rect(0, 0, width, height), ptr, height*stride, stride);
using (var btm = new Bitmap(width, height, stride, PixelFormat.Format1bppIndexed, ptr))
{
// Clone the bitmap so that we can dispose it and
// release the unmanaged memory at ptr
return new Bitmap(btm);
}
}
finally
{
if (ptr != IntPtr.Zero)
Marshal.FreeHGlobal(ptr);
}
And load it back from the file:
try
{
var openFileDialog = new OpenFileDialog
{
CheckFileExists = true,
Multiselect = false,
DefaultExt = "txt",
InitialDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
if (openFileDialog.ShowDialog() == true)
{
string base64String;
using (FileStream stream = File.Open(openFileDialog.FileName, FileMode.Open))
{
using (var reader = new StreamReader(stream))
{
base64String = reader.ReadToEnd();
}
}
byte[] binaryData = Convert.FromBase64String(base64String);
var bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = new MemoryStream(binaryData);
bi.EndInit();
Logo.Source = bi;
}
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString(), "An error occured", MessageBoxButton.OK, MessageBoxImage.Warning);
}
Here is a short code sequence that reads a JPG file into a byte array, creates a BitmapSource from it, then encodes it into a base64 string and writes that to file.
In a second step, the base64 string is read back from the file, decoded and a second BitmapSource is created.
The sample assumes that there is some XAML with two Image elements named image1 and image2.
Step 1:
var imageFile = #"C:\Users\Clemens\Pictures\DSC06449.JPG";
var buffer = File.ReadAllBytes(imageFile);
using (var stream = new MemoryStream(buffer))
{
image1.Source = BitmapFrame.Create(
stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
var base64File = #"C:\Users\Clemens\Pictures\DSC06449.b64";
var base64String = System.Convert.ToBase64String(buffer);
File.WriteAllText(base64File, base64String);
Step 2:
base64String = File.ReadAllText(base64File);
buffer = System.Convert.FromBase64String(base64String);
using (var stream = new MemoryStream(buffer))
{
image2.Source = BitmapFrame.Create(
stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
In case you need to encode an already existing BitmapSource into a byte array, use code like this:
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
using (var stream = new MemoryStream())
{
encoder.Save(stream);
buffer = stream.ToArray();
}

How to check File Size or dimension?

var dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "(*.JPG;*.GIF)|*.JPG;*.GIF";
dlg.ShowDialog();
if (string.IsNullOrEmpty(dlg.FileName)) return;
var fs = new FileStream(dlg.FileName, FileMode.Open, FileAccess.Read);
var data = new byte[fs.Length];
fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
I am using this code but not find how to find size or dimension of image?
Answered as a part of this question: Limit image size
string filename = // get it from OpenFileDialog
var length = new FileInfo(filename).Length;
Image img = Image.FromFile(filename);
var w = img.Width;
var h = img.Height;
use FileInfo given path of this file and use Length as
var dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "(*.JPG;*.GIF)|*.JPG;*.GIF";
dlg.ShowDialog();
if (string.IsNullOrEmpty(dlg.FileName))
return;
FileInfo info = new FileInfo(dlg.FileName);
Console.Write("Length In Bytes:"+info.Length);

How to save BitmapImage via SaveFileDialog from WPF?

The way I try implement it via standart Windows.Forms (to get valide DialogResult.OK)
System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
// dlg.DefaultExt = ".jpg"; // Default file extension
dlg.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
if(dlg.ShowDialog()== System.Windows.Forms.DialogResult.OK)
if (dlg.DialogResult.HasValue && splashDialog.DialogResult.Value)
{
string fName = dlg.FileName;
if (dlg.FileName != "")
{
System.IO.Stream fileStream = (System.IO.FileStream)dlg.OpenFile();
fileStream.Close();
}
}
This is using Windows forms but it saves blank image((
You can do something like that:
var encoder = new JpegBitmapEncoder(); // Or PngBitmapEncoder, or whichever encoder you want
encoder.Frames.Add(BitmapFrame.Create(yourImage));
using (var stream = dlg.OpenFile())
{
encoder.Save(stream);
}
BTW, there is a SaveFileDialog in WPF too, you don't have to use the one from Windows Forms
For WPF code will be like :
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document";
dlg.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
if (dlg.ShowDialog() == true)
{
var encoder = new JpegBitmapEncoder(); // Or PngBitmapEncoder, or whichever encoder you want
encoder.Frames.Add(BitmapFrame.Create(bi));
using (var stream = dlg.OpenFile())
{
encoder.Save(stream);
}
}
Here bi is the BitmapImage

how i pass image in This function

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
Nullable<bool> result = dlg.ShowDialog(); // Show open file dialog box
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
txtBrowse.Text = filename;
}
ImageSource imageSource = new BitmapImage(new Uri(txtBrowse.Text));
imgImageAdlut.Source = imageSource; ;
byte[] array1 = null;
//array1 = imageToByteArray();
}
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
Try this:
var img = new System.Drawing.Bitmap(#"D:\Your image path\your image.bmp");
byte[] array1 = imageToByteArray(img);

Categories