Why is not an image inserted in the RichTextBox? - c#

I tried to insert image into RichTextBox by clicking the button.
I referred this post - How can I insert an image into a RichTextBox? and made the source code
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
f.Filter = "BMP (*.bmp)|*.bmp|JPEG (*.jpg, *.jpeg, *.jpe, *.jfif)|*.jpg;*.jpeg;*.jpe;*.jfif|GIF (*.gif)|*.gif|PNG (*.png)|*.png|All files|*.bmp;*.jpg;*.jpeg;*.jpe;*.jfif;*.gif;*.png";
if (f.ShowDialog() == DialogResult.OK)
{
// Get type of the file
string typeOfFile = "";
Stack<char> typeParse = new Stack<char>();
int pointer = f.FileName.Length - 1
while (pointer > 0 && f.FileName[pointer] != '.')
typeParse.Push(f.FileName[pointer--]);
while (typeParse.Count > 0)
typeOfFile += typeParse.Pop();
typeOfFile = typeOfFile.ToLower();
// Convert Image to byte[]
Image image = Image.FromFile(f.FileName);
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
// Insert the image data in RichTextBox which is converted to hex from byte[]
// by using BitConverter.ToString(ms.ToArray();
StringBuilder imageRTF = new StringBuilder();
imageRTF.Append(#"{\pict\" + typeOfFile + #"blip\picw" + image.Width + #"\pich" + image.Height);
imageRTF.Append(#"\picwgoal" + image.Width + #"\pichgoal" + image.Height);
imageRTF.Append(#" " + BitConverter.ToString(ms.ToArray()) + #"}");
string rtf1 = richTextBox1.Rtf.Trim().TrimEnd('}');
string rtf2 = imageRTF.ToString();
richTextBox1.Rtf = rtf1 + rtf2;
}
}
but when I executed and opened png file, only one line break was inserted in RichTextBox..
What is wrong??

Related

How to save the image while updating the BARCODE?

When I am saving an image, it is getting saved by the Barcode name.
But If I modify the barcode name, then the image is gone, not saving.
I have noticed while debugging that the if(System.IO.File.Exists(imageFilePath)) is not executing when I am updating the barcode. But at the time of saving a new one, its executing.
How to correct this?
Updating code
public object Update(ItemEntity item)
{
var val = _itemRepository.Save(item);
if (item.ImageFileName != string.Empty || item.ImageOriginalFileName != string.Empty)
{
string result = JsonConvert.SerializeObject(val);
var definition = new { Success = false, EntryMode = string.Empty, BarCode = string.Empty, ItemCode = string.Empty };
var info = JsonConvert.DeserializeAnonymousType(result, definition);
if (info.Success)
{
if (!string.IsNullOrEmpty(item.ImageOriginalFileName))
this.SaveImage(item.ImageFileName, (item.ImageOriginalFileName == "BARCODE" ? info.ItemCode : item.ImageOriginalFileName == "BARCODEYes" ? item.Barcode : item.ImageOriginalFileName));
}
}
if (item.DeleteImageFileName != string.Empty && item.ImageFileName == string.Empty) // Image file removed but no new image file is uploaded[Bug Id :34754 -No image is uploaded, when a user re-uploads an image after deleting a previous one.]
{
this.DeleteImage(item.DeleteImageFileName);
}
return val;
}
Saving Code
public void SaveImage(string fileName, string originalFileName)
{
string tempFileName = fileName;
if (!string.IsNullOrEmpty(tempFileName))
{
// move file from temp location to actual loation
var webAppPath = System.Web.Hosting.HostingEnvironment.MapPath("~");
var splitPath = webAppPath.Split("\\".ToCharArray()).ToList();
var upLevel = splitPath.Count - 1; // one level up
splitPath = splitPath.Take(upLevel).ToList();
var UIFolder = "WebUI";
splitPath.AddRange(new string[] { UIFolder, "Temp", "ImageUpload", CurrentSession.UserId.Value.ToString(), "ItemImage" });
var webUIPath = splitPath.Aggregate((i, j) => i + "\\" + j);
var imageFilePath = Path.Combine(webUIPath.EnsureEndsWith('\\'), tempFileName);
if (System.IO.File.Exists(imageFilePath))
{
splitPath = webAppPath.Split("\\".ToCharArray()).ToList();
upLevel = splitPath.Count - 1; // one level up
splitPath = splitPath.Take(upLevel).ToList();
splitPath.AddRange(new string[] { "Shared", "ItemImage" });
webUIPath = splitPath.Aggregate((i, j) => i + "\\" + j);
// Check existence of folder, create if not found and Delete-Create if found
if (!Directory.Exists(webUIPath))
{
Logger.Debug("Create directory :" + webUIPath);
Directory.CreateDirectory(webUIPath);
}
originalFileName = originalFileName + ".jpg";
var imagDestPath = Path.Combine(webUIPath.EnsureEndsWith('\\'), originalFileName);
if (File.Exists(imagDestPath))
{
GC.Collect();
GC.WaitForPendingFinalizers();
Logger.Debug("Delete File :" + imagDestPath);
File.Delete(imagDestPath);
}
byte[] bytes = System.IO.File.ReadAllBytes(imageFilePath);
FileStream fs = new FileStream(imagDestPath, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(bytes);
bw.Close();
}
}
}

How to display the count in datagridview using windows forms

In my application i am displaying the messages if file is uploaded successfully and at the same time i am displaying the message that it is not uploaded in a message box.
The problem is i need to click ok button in message box each and every time when the message occours. Suppose if 40 files are not inserted i need to click ok button for 40 times. I need to display the files which are inserted and which are not inserted at a time in a datagridview. how can i do this.
if (ErrorMessage == 0)
{
Ffname += path + "-" + "Uploaded successfully" + "\n";
}
else
{
NotInsFiles += path + " - " + "Not Inserted" + "\n";
}
lbluplodedfile.Text = TabNotIns;
if (Ffname != null || Ffname != "")
{
MessageBox.Show(Ffname);
lbluplodedfile.Text = Ffname;
}
else
{
MessageBox.Show(NotInsFiles);
}
I think you have to do loop around your upload file and you have to adding in this loop the
if (ErrorMessage == 0)
{
Ffname += path + "-" + "Uploaded successfully" + "\n";
}
else
{
NotInsFiles += path + " - " + "Not Inserted" + "\n";
}
and when the loop finish try to show message box
To display image in datagridview you have to insert column of type DataGridViewImageColumn and after you can display image inside.
private void ImgToDataGridView()
{
/* List of path of img */
List<string> pathImgUpload = new List<string>();
List<string> pathNotInsert = new List<string>();
/* Just for my test */
pathImgUpload.Add("./abc.png");
pathImgUpload.Add("./abc.png");
pathImgUpload.Add("./abc.png");
pathImgUpload.Add("./abc.png");
pathNotInsert.Add("./abc.png");
pathNotInsert.Add("./abc.png");
pathNotInsert.Add("./abc.png");
pathNotInsert.Add("./abc.png");
pathNotInsert.Add("./abc.png");
/* Creation of columns for the good and bad img */
DataGridViewImageColumn colImgUpload = new DataGridViewImageColumn();
DataGridViewImageColumn colImgNotInsert = new DataGridViewImageColumn();
dataGridView1.Columns.Add(colImgUpload);
dataGridView1.Columns.Add(colImgNotInsert);
/* Max of size of pathImgUpload and pathNotInsert */
var lineadd = pathImgUpload.Count > pathNotInsert.Count ? pathImgUpload.Count : pathNotInsert.Count;
/* Create the good number of line (-1 because a first line is already in datagridview)*/
for(int i = 0; i <lineadd - 1; i++)
{
dataGridView1.Rows.Add();
}
/* adding good img */
for (int i = 0; i < pathImgUpload.Count(); i++)
{
string path = pathImgUpload[i];
var img = new Bitmap(path);
dataGridView1.Rows[i].Cells[0].Value = img;
}
/* adding bad img */
for(int i = 0; i < pathNotInsert.Count();i++)
{
string path = pathNotInsert[i];
var img = new Bitmap(path);
dataGridView1.Rows[i].Cells[1].Value = img;
}
}

How to close a file handle byte[] firstHash = MD5.Create().ComputeHash(f1.OpenRead());

I have a piece of code which works nicely. However I need to close the file so I can perform file.move() function, this doesn't work because the file is used by another process. I need to use the correct file handle - can you guide me in the right direction?
static void DSCheckForDuplicates(string incomingfolder, string incomingarchivefolder, string quarantinefolder)
{
string[] F1 = Directory.GetFiles(incomingfolder);
string fname = "";
long FileOne;
long FileTwo;
bool FilesAreTrullyIdentical;
string FileStatusValue = "";
string Result = "";
string NewLocation = "";
foreach (string fileName in F1)
{
// FILE EXCLUSION LIST FROM DUPLICATE FILE CHECKS
if (fileName.Contains("xxx.DAT") || fileName.Contains("xxx.txt") || fileName.Contains("OrderHead.txt") )
{
Console.WriteLine("\nKnown file type..");
}
else
{
fname = Path.GetFileName(fileName);
FilesAreTrullyIdentical = false;
Console.WriteLine("Files present : The file is {0}...Press any key\n", fileName);
//Console.ReadKey();
if (File.Exists(incomingarchivefolder + #"\" + fname))
{
DuplicateFlag = true;
FileStatusValue = "DuplicateFilename";
DuplicateFileCounter++;
Narative += string.Format("\n________________________________________________________________________________________________________________\nFile Exception :{0}\n####################\n", DuplicateFileCounter );
Narative += string.Format ("Same filename exists in the two compared directories, Checking potential duplicate file contents in :{0}................\n", fileName);
FileInfo f1 = new FileInfo(fileName);
FileOne = f1.Length;
FileInfo f2 = new FileInfo(incomingarchivefolder + #"\" + fname);
FileTwo = f2.Length;
//if (FileOne == FileTwo)
//{
byte[] firstHash = MD5.Create().ComputeHash(f1.OpenRead());
byte[] secondHash = MD5.Create().ComputeHash(f2.OpenRead());
for (int i = 0; i < firstHash.Length; i++)
{
FilesAreTrullyIdentical = true;
if (firstHash[i] != secondHash[i])
FilesAreTrullyIdentical = false;
}
if (FilesAreTrullyIdentical == true)
{
FileStatusValue = "DuplicationFileNameDuplicateContents";
Console.WriteLine("Processed : WARNING!!! identical FILES contents FOUND {0}\n and {1}\n..............\n", fileName, incomingarchivefolder + #"\" + fname);
Narative += string.Format("\tProcessed : Please delete from incoming, WARNING!!! identical FILES contents\n\nPLEASE DELETE FILE:\t{0}..............\n", fileName);
Result = Path.GetFileName(fileName);
NewLocation += quarantinefolder + "\\" + Result;
Console.WriteLine("\n\n {0} ->\nMoving to {1} , press any key", fileName, NewLocation);
Console.ReadKey();
//File.Move(fileName, NewLocation); // THIS DOESNT WORK
You could capture the stream from f1.OpenRead() into a variable & pass that calling Close() when your done, instead however you should put the stream and MD5 reference within a using construct as currently you leave them undisposed. (This will also close the stream for you)
byte[] firstHash;
using (var stream = f1.OpenRead())
using (var md5 = MD5.Create())
{
firstHash = md5.ComputeHash(stream);
}

How to add same image in different resolution to different database columns in c# ASP.NET

I have a project in which, there is a Images on page with 400*300 resolution. When I hover Image, I have <a> and it opens as a full screen.
Now, when I upload an image, i save it to database column ITM_PATH. And there is another column ITM_LARGE. Now I want to do that, if I upload an image, the simple image will be stored at ITM_PATH and the same image but with 2400*1594 resolution in ITM_LARGE column. I have searched this but I got no solution.
Code for Upload Image:
protected void btnSubmit_Click(object sender, EventArgs e)
{
HttpFileCollection fileCollection = Request.Files;
string fileName="";
string largeFile = "";
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile uploadfile = fileCollection[i];
fileName = Path.GetFileName(uploadfile.FileName);
if (uploadfile.ContentLength > 0)
{
uploadfile.SaveAs(Server.MapPath("~/Photo-Upload/") + fileName);
lblMessage.Text += fileName + "Saved Successfully<br>";
fileName = "Photo-Upload/" + fileName;
}
}
using (Bitmap bitmap = (Bitmap)System.Drawing.Image.FromFile(fileName))
{
using (Bitmap newbitmap = new Bitmap(bitmap))
{
newbitmap.SetResolution(2400, 1594);
newbitmap.Save(fileName + "Large", ImageFormat.Jpeg);
largeFile = newbitmap.ToString(); ;
}
}
int _Itm_Id = GetMaxNo();
if (_Itm_Id > 0)
{
ConnectDataBase();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SP_GENERAL";
cmd.Parameters.AddWithValue("#SP_STATUS", "INSERT_ITM");
cmd.Parameters.AddWithValue("#ITM_ID", _Itm_Id);
cmd.Parameters.AddWithValue("#ITM_CAT_ID", ddlCategory.SelectedValue);
cmd.Parameters.AddWithValue("#ITM_NAME", txtItemName.Text);
cmd.Parameters.AddWithValue("#ITM_PATH", fileName);
cmd.Parameters.AddWithValue("#ITM_LARGE", largeFile);
//cmd.Parameters.AddWithValue("#ITM_PRICE", Convert.ToDecimal(txtPrice.Text));
int retval = cmd.ExecuteNonQuery();
if (retval > 0)
lblMessage.Text = "Record Successfully Inserted!!!";
else
lblMessage.Text = "Server Error!!! Please Try Again...";
ClearAll();
}
}
i am retrieving image in repeater by getting its url from database column.
EDIT
I searched for the same, and found bitmap as a solution, so i added that code, but file not found exception is coming. Any other idea or edits??
Exception is coming at first line of bitmap
Try Below Code.
protected void btnSubmit_Click(object sender, EventArgs e) {
HttpFileCollection fileCollection = Request.Files;
string fileName = "";
for (int i = 0; i < fileCollection.Count; i++) {
HttpPostedFile uploadfile = fileCollection[i];
fileName = Path.GetFileName(uploadfile.FileName);
if (uploadfile.ContentLength > 0) {
uploadfile.SaveAs(Server.MapPath("~/Photo-Upload-Large/") + fileName);
lblMessage.Text += fileName + "Saved Successfully<br>";
//Store Crope Image
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath("~/Photo-Upload-Large/") + fileName);
int newwidthimg = 400;
float AspectRatio = (float)image.Size.Width / (float)image.Size.Height;
int newHeight = Convert.ToInt32(newwidthimg / AspectRatio);
Bitmap thumbnailBitmap = new Bitmap(newwidthimg, newHeight);
Graphics thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newwidthimg, newHeight);
thumbnailGraph.DrawImage(image, imageRectangle);
thumbnailBitmap.Save(Server.MapPath("~/Photo-Upload-Thumb/"), ImageFormat.Jpeg);
thumbnailGraph.Dispose();
thumbnailBitmap.Dispose();
image.Dispose();
}
}
int _Itm_Id = GetMaxNo();
if (_Itm_Id > 0) {
ConnectDataBase();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SP_GENERAL";
cmd.Parameters.AddWithValue("#SP_STATUS", "INSERT_ITM");
cmd.Parameters.AddWithValue("#ITM_ID", _Itm_Id);
cmd.Parameters.AddWithValue("#ITM_CAT_ID", ddlCategory.SelectedValue);
cmd.Parameters.AddWithValue("#ITM_NAME", txtItemName.Text);
cmd.Parameters.AddWithValue("#ITM_PATH", fileName);
cmd.Parameters.AddWithValue("#ITM_LARGE", fileName);
//cmd.Parameters.AddWithValue("#ITM_PRICE", Convert.ToDecimal(txtPrice.Text));
int retval = cmd.ExecuteNonQuery();
if (retval > 0)
lblMessage.Text = "Record Successfully Inserted!!!";
else
lblMessage.Text = "Server Error!!! Please Try Again...";
ClearAll();
}
}

Cannot delete file in C#.net windows application

I am first creating Bitmap image file and saving it to some temp location. Later using that file to read in BitmapImage object to compare it with other file. Once comparison is done, I want to delete file but then it throws exception that file is being used by another process. How can I delete this file?
Here is my code:
private void btnLogin_Click(object sender, EventArgs e)
{
string strPath = AppDomain.CurrentDomain.BaseDirectory;
GC.Collect();
if (txtLoginImage.Text != "")
{
string strFileName = txtLoginImage.Text.Substring(txtLoginImage.Text.LastIndexOf('\\') + 1);
Bitmap MainImg = new System.Drawing.Bitmap(txtLoginImage.Text);
Bitmap NewImage = ConvertToGrayScale(MainImg);
NewImage.Save(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\Temp\\" + strFileName, System.Drawing.Imaging.ImageFormat.Bmp);
NewImage.Dispose();
Uri SourceUri = new Uri(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\Temp\\" + strFileName);
BitmapImage source = new BitmapImage();
source.UriSource = SourceUri;
IrisSystem.Class.BLL.User_BLL ubll = new IrisSystem.Class.BLL.User_BLL();
DataSet dsUserData= ubll.getlist();
bool isMatchFound = false;
if (dsUserData != null && dsUserData.Tables.Count > 0)
{
foreach (DataRow item in dsUserData.Tables[0].Rows)
{
Uri TargetUri = new Uri(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\Grayscale\\" + item["GrayScaleImgName"]);
BitmapImage Target = new BitmapImage(TargetUri);
if (source.IsEqual(Target))
{
IrisSystem.frmHome frm= new IrisSystem.frmHome();
frm.strFullName = item["FullName"].ToString();
frm.ShowDialog();
Form.ActiveForm.Close();
isMatchFound = true;
break;
}
Target = null;
}
if (!isMatchFound)
MessageBox.Show("Invalid Credential..","Invalid Operation");
}
File.Delete(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\Temp\\" + strFileName);
}
else
MessageBox.Show("Please select image", "Login Error");
}
You need to make sure that your Bitmap objects are disposed properly.
You are not disposing the MainImg object. you need to use using {} block to make sure that objects are disposed properly.
Replace This:
Bitmap MainImg = new System.Drawing.Bitmap(txtLoginImage.Text);
Bitmap NewImage = ConvertToGrayScale(MainImg);
NewImage.Save(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\Temp\\"
+ strFileName, System.Drawing.Imaging.ImageFormat.Bmp);
NewImage.Dispose();
With This:
using(Bitmap MainImg = new System.Drawing.Bitmap(txtLoginImage.Text))
using(Bitmap NewImage = ConvertToGrayScale(MainImg))
{
NewImage.Save(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\Temp\\" +
strFileName, System.Drawing.Imaging.ImageFormat.Bmp);
}
EDIT:
Replace This:
BitmapImage source = new BitmapImage();
source.UriSource = SourceUri;
With This:
BitmapImage source = new BitmapImage();
source.BeginInit();
source.UriSource = SourceUri;
source.EndInit();

Categories