I am Trying to create a social website. If anyone posted an image the it will detect all the faces in the image and draw a square in the face. Then i want to display the image. My problem is how to preview the image without saving it into a folder. Here is My code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
public partial class User_AddPhoto : System.Web.UI.Page
{
private HaarCascade haar;
string base64String;
Stream fs;
protected void Page_Load(object sender, EventArgs e)
{
string location = Server.MapPath("~/Bin/") + "haarcascade_frontalface_default.xml";
haar = new HaarCascade(location);
}
protected void Button1_Click(object sender, EventArgs e)
{
/*Image Preview */
//Session["Image"] = FileUpload1.PostedFile;
//fs = FileUpload1.PostedFile.InputStream;
//BinaryReader br = new BinaryReader(fs);
//byte[] bytes = br.ReadBytes((Int32)fs.Length);
//base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
//Image1.ImageUrl = "data:image/png;base64," + base64String;
/***/
////////////////////////////*Detect Face*///////////////////////////
//DetectFaces();
Bitmap bmpImage = new Bitmap(fs);
Image<Bgr, byte> InputFrame = new Image<Bgr, byte>(bmpImage);
Image<Gray, byte> grayFrame = (InputFrame).Convert<Gray, byte>();
MCvAvgComp[][] faces = grayFrame.DetectHaarCascade(
haar,
1.4,
8,
HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
new Size(20, 20)
);
foreach (MCvAvgComp face in faces[0])
{
InputFrame.Draw(face.rect, new Bgr(Color.Red), 3);
}
Bitmap Display = InputFrame.ToBitmap();
//Display.Save(Server.MapPath("~/Images/aaa.jpg"));
//////////////////////////////////**/////////////////////////////////
/* Photo Inserting Into Folder and Into Database*/
BLUser blUser = new BLUser();
string UserId=Session["UserId"].ToString();
string date = DateTime.Now.ToString("mm-dd_hh_mm_ss");
if (FileUpload1.HasFile)
{
string Extension = Path.GetExtension(FileUpload1.FileName);
string ImageName = date;
string PhotoUrl="~/Images/Posts/" + ImageName + Extension;
FileUpload1.SaveAs(Server.MapPath("~/Images/Posts/" + ImageName + Extension));
blUser.PostImage(PhotoUrl,UserId);
}
/**/
}
}
But i am in stuck to preview the image. Please Help me someone. Thanks In advance :)
to save the image in sql server
Byte[] imgByte = null;
if (FileUpload1.HasFile && FileUpload1.PostedFile != null)
{
HttpPostedFile File = FileUpload1.PostedFile;
imgByte = new Byte[File.ContentLength];
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
connection = new SqlConnection(ConfigurationManager.ConnectionStrings ["ConnectionString"].ConnectionString.ToString());
connection.Open();
string sql = "INSERT INTO Table1(title,image) VALUES(#theTitle, #theImage) SELECT ##IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("#theTitle", txtTitle.Text);
cmd.Parameters.AddWithValue("#theImage", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblStatus.Text = String.Format("ID is {0}", id);
Image1.ImageUrl = "~/DisplayImg.ashx?id=" + id;
To show the saved image in browser(Handler)
public void ProcessRequest (HttpContext context)
{
Int32 theID;
if (context.Request.QueryString["id"] != null)
theID = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = DisplayImage(theID);
byte[] buffer = new byte[2048];
int byteSeq = strm.Read(buffer, 0, 2048);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}
public Stream DisplayImage(int theID)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString());
string sql = "SELECT image FROM Table1 WHERE id = #ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ID", theID);
connection.Open();
object theImg = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])theImg);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
public bool IsReusable {
get
{
return false;
}
}
For more details :http://www.aspnettutorials.com/tutorials/database/saving-retrieving-image-cs/
#john
It is possible to using binary Reader to convert image as a byte data and assign to image source.
refer below link.
http://mehtawebsolution.com/blog/display-image-preview-without-saving-file-to-folder-asp-net/
Related
I followed the code from this guide in order to resize an image before storing it in a database:
https://www.aspsnippets.com/questions/876401/Resize-image-and-save-into-Database-with-Binary-format-using-C-and-VBNet-in-ASPNet/
Here is the code:
protected void Save(object sender, EventArgs e)
{
if (fuImage.HasFile)
{
Byte[] bytes;
string contentType = fuImage.PostedFile.ContentType;
string fileName = Path.GetFileName(fuImage.FileName);
string filePath = fuImage.PostedFile.FileName;
System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
// Resize image
using (System.Drawing.Image thumbnail = image.GetThumbnailImage(130, 170, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
{
using (MemoryStream memoryStream = new MemoryStream())
{
thumbnail.Save(memoryStream, ImageFormat.Png);
bytes = new Byte[memoryStream.Length];
memoryStream.Position = 0;
memoryStream.Read(bytes, 0, (int)bytes.Length);
}
}
// Insert uploaded image to Database
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO tblFiles1 VALUES (#Name, #ContentType, #Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", fileName);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
// Display image after upload to Database
Image1.Visible = true;
byte[] byteData = (byte[])GetData("SELECT Data FROM tblFiles1").Rows[0]["Data"];
string base64String = Convert.ToBase64String(byteData, 0, byteData.Length);
Image1.ImageUrl = "data:image/png;base64," + base64String;
}
public bool ThumbnailCallback()
{
return false;
}
The problem I am getting however, is once I select an image using the FileUploader and try to run the save method, I get a System.IO.FileNotFoundException at the line:
System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
Thanks in advance!
The FileName property is the file name property from the client (https://learn.microsoft.com/en-us/dotnet/api/system.web.httppostedfilebase.filename?view=netframework-4.8#System_Web_HttpPostedFileBase_FileName) so you can't load the file using that property. I can upload an image from c:\yfeyhcdrt\image.png, but this folder will probably not exist on your server. You should load it using the InputStream property instead using https://learn.microsoft.com/en-us/dotnet/api/system.drawing.image.fromstream?view=windowsdesktop-5.0
When I get a Bitmap image from SQL Server DB to display it in a PictureBox, I get an exception:
Parameter is not valid error
Here's my code:
public void FillHotMenu(int key, string connection, string logdir)
{
try
{
SqlConnection conn = new SqlConnection(connectionstr);
conn.Open();
SqlCommand cmd = new SqlCommand("Pm_R_GetHotMenus", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#keyid", key);
SqlDataReader read = cmd.ExecuteReader();
flowLayoutPanel1.Controls.Clear();
while (read.Read())
{
byte[] b = (byte[])(read["KeyBitmap"]);
if (b.Length > 1)
{
PictureBox pic = new PictureBox();
pic.Size = new Size(flowLayoutPanel1.Width / 4, flowLayoutPanel1.Height / 4);
string s = read["KeyBitmap"].ToString();
using (MemoryStream ms = new MemoryStream(b))
{
Bitmap image = new Bitmap(ms); // *** I'm getting error here
pic.Image = image;
}
pic.SizeMode = PictureBoxSizeMode.StretchImage;
flowLayoutPanel1.Controls.Add(pic);
}
else if (read["KeyTextValue"].ToString() != "")
{
textvalue = "";
PictureBox pic = new PictureBox();
pic.Size = new Size(flowLayoutPanel1.Width / 4, flowLayoutPanel1.Height / 4);
textvalue = read["KeyTextValue"].ToString();
pic.Paint += new PaintEventHandler(pictureBox1_Paint);
flowLayoutPanel1.Controls.Add(pic);
}
}
conn.Close();
}
catch (Exception ex)
{
string logstr = ex.InnerException == null ? "" : ex.InnerException.Message;
log.append("ERROR:" + ex.Message + "-->" + logstr, logdirectory);
MessageBox.Show(ex.Message);
Environment.Exit(0);
}
}
How can I solve this problem?
Edit:
I've tried this code with no exceptions but nothing is shown in the PictureBox:
var ms = new MemoryStream(b);
ms.Seek(0, SeekOrigin.Begin);
ms.Position = 0;
byte[] imagebytes = ms.ToArray();
Bitmap bitmap = new Bitmap(pic.Width, pic.Height);
bitmap.Save(ms, ImageFormat.Png);
pic.Image = Image.FromStream(ms);
pic.SizeMode = PictureBoxSizeMode.StretchImage;
This question already has an answer here:
No imaging component suitable to complete the operation was found WPF vb.net
(1 answer)
Closed 4 years ago.
I'm trying to load image from my .mdb database in WPF. I'm using this code :
public void loadimg()
{
con.Open();
OleDbCommand cmd = new OleDbCommand("Select * from recents", con);
DataTable table = new DataTable;
OleDbDataAdapter adap = new OleDbDataAdapter(cmd);
adap.Fill(table);
if (table.Rows.Count <= 0)
{
MsgBox("nooo");
}
else
{
MemoryStream stream = new MemoryStream();
StreamWriter stm;
BinaryWriter writer = new BinaryWriter(stream);
int bufferSize = 100;
byte[] outByte = new byte[bufferSize + 1];
long retval;
long startIndex = 0;
string pubID = "";
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
reader.Read();
while (reader.Read())
{
startIndex = 0;
retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);
while (retval == bufferSize)
{
writer.Write(outByte);
writer.Flush();
startIndex += bufferSize;
retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);
}
writer.Write(outByte, 0, (int)retval - 1);
writer.Flush();
}
reader.Close();
con.Close();
stream.Position = 0;
stream.Seek(0, SeekOrigin.Begin);
System.Drawing.Image _Image = System.Drawing.Image.FromStream(stream);
image1.Source = System.Windows.Media.Imaging.BitmapFrame.Create(stream);
}
}
The code above returns an error :
No imaging component suitable to complete this operation was found.
I spent hours trying to figure out how to fix it.Any help would be highly appreciated.
Update
In the comments, i was asked if i inserted the data properly..Well,here's the code i used to insert the data :
public void adddata()
{
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert into recents(Pic)values(#pic)", con);
byte[] data;
System.Drawing.Image myimage = System.Drawing.Image.FromFile("E:\\19686468_1419770068104721_1127495277_o.png");
using (MemoryStream ms = new MemoryStream())
{
myimage.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
data = ms.ToArray();
}
cmd.Parameters.AddWithValue("#pic", data);
cmd.ExecuteNonQuery();
con.Close();
}
Please help me out!
Fixed it...For anyone who faces this error in future :
Make sure you're inserting the data in the proper way(sometimes corrupted data in the db causes such errors)
2 . You don't need to do some heavy coding to convert the image to byte!
Finally,let's code :
public void loadimg()
{
con.Open();
OleDbCommand cmd = new OleDbCommand("Select * from recents", con);
OleDbDataReader _dr;
_dr = cmd.ExecuteReader;
byte[] _photo;
while (_dr.Read())
{
try
{
_photo = (byte[])_dr(1);
BitmapImage bi = new BitmapImage();
using (MemoryStream strm = new MemoryStream(_photo))
{
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.StreamSource = strm;
bi.EndInit();
}
image1.Source = bi;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
This question already has answers here:
Byte array to image conversion
(14 answers)
Display image from byte[ ]
(1 answer)
Closed 5 years ago.
I'm new to WPF programming and Microsoft SQL server. I want to insert and retrieve an image to/from a database. I learned about converting an image (Windows.Controls.Image) to byte[] and storing it to a database, but I couldn't convert from byte[] to Image back to display it in a WPF window.
private Image byteArrayToImage(byte[] arr)
{
MemoryStream stream = new MemoryStream();
stream.Write(arr, 0, arr.Length);
stream.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(stream); // Exception
BitmapImage returnImage = new BitmapImage();
returnImage.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
returnImage.StreamSource = ms;
returnImage.EndInit();
Image ans = new Image();
ans.Source = returnImage;
return ans;
}
Output:
System.ArgumentException: 'Parameter is not valid.'
private byte[] imageToArray(System.Drawing.Image img) // Work well
{
MemoryStream ms = new MemoryStream();
FileInfo fi = new FileInfo(tempData); // File name
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] pic = ms.ToArray();
return pic;
}
first, create a static class for your PictureHelper. You must import the BitmapImage that is used in WPF, i think its the using System.Drawing.Imaging;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Threading;
using Application = System.Windows.Forms.Application;
using Size = System.Drawing.Size;
public static class PictureHelper
{
public static BitmapImage GetImage(object obj)
{
try
{
if (obj == null || string.IsNullOrEmpty(obj.ToString())) return new BitmapImage();
#region Picture
byte[] data = (byte[])obj;
MemoryStream strm = new MemoryStream();
strm.Write(data, 0, data.Length);
strm.Position = 0;
Image img = Image.FromStream(strm);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
return bi;
#endregion
}
catch
{
return new BitmapImage();
}
}
public static string PathReturner(ref string name)
{
string filepath = "";
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = false;
openFileDialog.Filter = #"Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.gif;*.png;*.jpg";
openFileDialog.RestoreDirectory = true;
openFileDialog.Title = #"Please select an image file to upload.";
MiniWindow miniWindow = new MiniWindow();
miniWindow.Show();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
filepath = openFileDialog.FileName;
name = openFileDialog.SafeFileName;
}
miniWindow.Close();
miniWindow.Dispose();
return filepath;
}
public static string Encryptor(this string safeName)
{
string extension = Path.GetExtension(safeName);
string newFileName = String.Format(#"{0}{1}{2}", Guid.NewGuid(), DateTime.Now.ToString("MMddyyyy(HHmmssfff)"), extension);
newFileName = newFileName.Replace("(", "").Replace(")", "");
return newFileName;
}
public static Bitmap ByteToBitmap(this byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}
public static byte[] BitmapToByte(this Image img)
{
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
return byteArray;
}
}
this is for retrieving the class (in my case, Candidate) with picture
public SortableBindingList<Candidate> RetrieveManyWithPicture(Candidate entity)
{
var command = new SqlCommand { CommandText = "RetrievePictureCandidates", CommandType = CommandType.StoredProcedure };
command.Parameters.AddWithValue("#CandidateId", entity.CandidateId).Direction = ParameterDirection.Input;
DataTable dt = SqlHelper.GetData(command); //this is where I retrieve the row from db, you have your own code for retrieving, so make sure it works.
var items = new SortableBindingList<Candidate>();
if (dt.Rows.Count <= 0) return items;
foreach (DataRow row in dt.Rows)
{
Candidate item = new Candidate();
item.CandidateId = row["CandidateId"].GetInt();
item.LastName = row["LastName"].GetString();
item.FirstName = row["FirstName"].GetString();
item.PictureId = row["PictureId"].GetInt();
item.PhotoType = PictureHelper.GetImage(row["Photo"]); //in my db, this is varbinary. in c#, this is byte[]
items.Add(item);
}
return items;
}
this is for uploading image from wpf to db which I used on my button
private void UploadButton_Click(object sender, EventArgs e)
{
string safeName = "";
string pathName = PictureHelper.PathReturner(ref safeName);
PictureViewModel vm = new PictureViewModel();
if (pathName != "")
{
safeName = safeName.Encryptor();
FileStream fs = new FileStream(pathName, FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, Convert.ToInt32(fs.Length));
fs.Close();
PicNameLabel.Text = safeName;
vm.Entity.Name = safeName; //this is the byte[]
Bitmap toBeConverted = PictureHelper.ByteToBitmap(data); //convert the picture before sending to the db
vm.Entity.Photo = PictureHelper.BitmapToByte(toBeConverted);
vm.Entity.Path = pathName;
CandidatePictureBox.Image = toBeConverted;
vm.Insert(vm.Entity);
}
}
this is the method to save the picture
public bool Insert(Picture entity)
{
var command = new SqlCommand();
try
{
command.CommandText = "AddPicture";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#Name", entity.Name).Direction = ParameterDirection.Input;
command.Parameters.AddWithValue("#Photo", entity.Photo).Direction = ParameterDirection.Input;
int result = SqlHelper.ExecuteNonQuery(command); //executenonquery will save the params to the db
return true;
}
catch (Exception)
{
return false;
}
}
I saved an image into mysql as Blob normally from visual studio windows 8.1 project but I need to retrieve this image and put it into Image tool.
This code below to insert image into Mysql:
public static void insertImage()
{
FileOpenPicker imagePicker = new FileOpenPicker
{
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.PicturesLibrary,
FileTypeFilter = { ".jpg", ".jpeg", ".png", ".bmp" }
};
StorageFile imageFile = await imagePicker.PickSingleFileAsync();
string a = imageFile.Name;
string FileName = a;
var inputStream = await imageFile.OpenSequentialReadAsync();
var readStream = inputStream.AsStreamForRead();
var buffer = new byte[readStream.Length];
await readStream.ReadAsync(buffer, 0, buffer.Length);
size = buffer.Length;
using (MySqlConnection connection = new MySqlConnection(
"server=localhost;database=familytree;uid=root;"))
{
connection.Open();
MySqlCommand update = new MySqlCommand("UPDATE node SET avatar = '" +
buffer + "' WHERE email = '" + email + "'", connection);
update.ExecuteNonQuery();
}
}
to store the picture :
private static async Task FileToByteArray(Uri sourceUri)
{
var file = await StorageFile.GetFileFromApplicationUriAsync(sourceUri);
using (var inputStream = await file.OpenSequentialReadAsync())
{
var readStream = inputStream.AsStreamForRead();
var buffer = new byte[readStream.Length];
await readStream.ReadAsync(buffer, 0, buffer.Length);
return buffer;
}
}
and to retrieve it:
private static async Task ConvertToImage(byte[] imageBytes)
{
var image = new BitmapImage();
using (var randomAccessStream = new InMemoryRandomAccessStream())
{
var dw = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
dw.WriteBytes(imageBytes);
await dw.StoreAsync();
image.SetSourceAsync(randomAccessStream);
}
return image;
}