I am having a problem when I try to upload the image on the folder and click upload,the image is not saved in 'UploadedFiles' folder.The 'UploadedFiles' folder is still empty and does not contain any picture.
This is my project directory of the saved image that it should go if it might helps:
//C:\Users\Drake\Documents\Visual Studio 2013\Projects\DigitalWaterMarkTest\DigitalWaterMarkTest\UploadFiles
protected void btnSave_Click(object sender, EventArgs e)
{
// Here We will upload image with watermark Text
string fileName = Guid.NewGuid() + Path.GetExtension(FU1.PostedFile.FileName);
Image upImage = Image.FromStream(FU1.PostedFile.InputStream);
upImage = ResizeBitmap((Bitmap)upImage, 400, 400);//new width
using (Graphics g = Graphics.FromImage(upImage))
{
// For Transparent Watermark Text
int opacity = 128; // range from 0 to 255
//SolidBrush brush = new SolidBrush(Color.Red);
SolidBrush brush = new SolidBrush(Color.FromArgb(opacity, Color.Black));
SolidBrush brush2 = new SolidBrush(Color.FromArgb(opacity, Color.Red));
Font font = new Font("Arial", 15);
g.DrawString(txtWatermarkText.Text.Trim(), font, brush, new PointF(80,160));
g.DrawString(txtWatermarkText.Text.Trim(), font, brush2, new PointF(200, 250));
upImage.Save(Path.Combine(Server.MapPath("~/UploadFiles"), fileName));
Image1.ImageUrl = "~/UploadFiles" + "//" + fileName;
}
}
Related
I'm trying to get webbrowser control as image. But when my code gives me a full screen image. I want to get only webbrowser image. How should I fix my code to get the right image?
Bitmap memoryImage;
private void button2_Click(object sender, EventArgs e)
{
Graphics myGraphics = webBrowser1.CreateGraphics();
Size s = webBrowser1.Size;
memoryImage = new Bitmap(webBrowser1.Width,webBrowser1.Height, myGraphics);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(webBrowser1.Location.X, webBrowser1.Location.Y, 0, 0, s);
memoryImage.Save("C:\\Users\\Koo\\Desktop\\NaverMap.png");
Use the following code - Which supported and does work, but not always works fine.
In some circumstances you will get a blank image screenshot(when there is a more complex html it loads, the more possible it fails)
using (var browser = new System.Windows.Forms.WebBrowser())
{
browser.DocumentCompleted += delegate
{
using (var pic = new Bitmap(browser.Width, browser.Height))
{
browser.DrawToBitmap(pic, new Rectangle(0, 0, pic.Width, pic.Height));
pic.Save(imagePath);
}
};
browser.Navigate(Server.MapPath("~") + htmlPath); //a file or a url
browser.ScrollBarsEnabled = false;
while (browser.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents();
}
}
Is there a way to crops image by removing borders of uniform color ?
EDIT: Based on the similar topic, I tried to use AForge.NET package - Extract biggest blob, it dint work.
I have tried using all the Blob extract functions and All I get is just the channel extract, I need to perform this after I do the Green channel extract. I even tried the extract Black just in case. That too dint work.
Here is my code that I have tried.
private void openToolStripMenuItem_Click(object sender, EventArgs e)// File-Open - Import image and show in PictureBox1
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Image";
dlg.Filter = "bmp files (*.bmp)|*.bmp";
if (dlg.ShowDialog() == DialogResult.OK)
{
ClearCurrentImage();
pictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
////------ AForge.NET sequence------//
//// create filter
//SaturationCorrection filter = new SaturationCorrection(-0.5f);
//// apply the filter
//filter.ApplyInPlace(image);
////------ AForge.NET sequence------//
// Pass original image to the channel extract filter
Bitmap image = new Bitmap(pictureBox1.Image);
//Create filters
ExtractChannel GreenChannel = new ExtractChannel(RGB.G);
//ExtractBiggestBlob BlobGreenChannel = new ExtractBiggestBlob();
//RotateBilinear RotateFilter = new RotateBilinear(30, true);
Shrink Blackfilter = new Shrink(Color.Black);
// ---------------- Apply filter ------------------//
Bitmap ChannelImage = GreenChannel.Apply(image);
//Bitmap BlobChannelImage = BlobGreenChannel.Apply(image);
//Bitmap RBCImage = RotateFilter.Apply(BlobGreenChannel.Apply(GreenChannel.Apply(image)));
//Bitmap BlobChannelImage = BlobGreenChannel.Apply(GreenChannel.Apply(image));
//Bitmap BRBCImage = Blackfilter.Apply(RotateFilter.Apply(BlobGreenChannel.Apply(GreenChannel.Apply(image))));
Bitmap BlackImage = Blackfilter.Apply(GreenChannel.Apply(image));
pictureBox2.Image = BlackImage;
}
dlg.Dispose();
}
I would like to fit the image in the smallest rectangle possible by cropping away all the black background. How can I achieve this?
I am following this tutorial and downloaded source code to practice, and it works. The problem occurs when I rewrite the code: just one image is added instead of all the selected images. What am I doing wrong here?
private void button1_Click(object sender, EventArgs e)
{
ofd.Filter = "Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF|" +
"All files (*.*)|*.*";
ofd.Multiselect = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
foreach (string name in ofd.FileNames)
{
PictureBox imageControl = new PictureBox();
imageControl.Width = 100;
imageControl.Height = 100;
Image.GetThumbnailImageAbort CallBck = new Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap = new Bitmap(name);
Image img = myBitmap.GetThumbnailImage(97, 97, CallBck, IntPtr.Zero);
imageControl.Image = img;
panel1.Controls.Add(imageControl);
}
}
}
I'll bet they are all being added but they're just all going on top of each other at location (0,0) in the panel (you should step through your code to check this though).
The solution: Either manually specify a location for each new PictureBox, or use a layout control such as a FlowLayoutPanel.
I have this problem when I drag to select region of the image in the picturebox more than two times and run the scanning. This is an OCR system.
region OCR(Tab4_Component)
//When user is selecting, RegionSelect = true
private bool RegionSelect = false;
private int x0, x1, y0, y1;
private Bitmap bmpImage;
private void loadImageBT_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = #"C:\Users\Shen\Desktop";
open.Filter = "Image Files(*.jpg; *.jpeg)|*.jpg; *.jpeg";
if (open.ShowDialog() == DialogResult.OK)
{
singleFileInfo = new FileInfo(open.FileName);
string dirName = System.IO.Path.GetDirectoryName(open.FileName);
loadTB.Text = open.FileName;
pictureBox1.Image = new Bitmap(open.FileName);
bmpImage = new Bitmap(pictureBox1.Image);
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
//User image selection Start Point
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
RegionSelect = true;
//Save the start point.
x0 = e.X;
y0 = e.Y;
}
//User select image progress
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
//Do nothing it we're not selecting an area.
if (!RegionSelect) return;
//Save the new point.
x1 = e.X;
y1 = e.Y;
//Make a Bitmap to display the selection rectangle.
Bitmap bm = new Bitmap(bmpImage);
//Draw the rectangle in the image.
using (Graphics g = Graphics.FromImage(bm))
{
g.DrawRectangle(Pens.Red, Math.Min(x0, x1), Math.Min(y0, y1), Math.Abs(x1 - x0), Math.Abs(y1 - y0));
}
//Temporary display the image.
pictureBox1.Image = bm;
}
//Image Selection End Point
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
// Do nothing it we're not selecting an area.
if (!RegionSelect) return;
RegionSelect = false;
//Display the original image.
pictureBox1.Image = bmpImage;
// Copy the selected part of the image.
int wid = Math.Abs(x0 - x1);
int hgt = Math.Abs(y0 - y1);
if ((wid < 1) || (hgt < 1)) return;
Bitmap area = new Bitmap(wid, hgt);
using (Graphics g = Graphics.FromImage(area))
{
Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
}
// Display the result.
pictureBox3.Image = area;
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");
singleFileInfo = new FileInfo("C:\\Users\\Shen\\Desktop\\LenzOCR\\TempFolder\\tempPic.jpg");
}
private void ScanBT_Click(object sender, EventArgs e)
{
var folder = #"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";
DirectoryInfo directoryInfo;
FileInfo[] files;
directoryInfo = new DirectoryInfo(folder);
files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);
var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
processImagesDelegate.BeginInvoke(files, null, null);
//BackgroundWorker bw = new BackgroundWorker();
//bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
//bw.RunWorkerAsync(bw);
//bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
private void ProcessImages2(FileInfo[] files)
{
var comparableImages = new List<ComparableImage>();
var index = 0x0;
foreach (var file in files)
{
if (exit)
{
return;
}
var comparableImage = new ComparableImage(file);
comparableImages.Add(comparableImage);
index++;
}
index = 0;
similarityImagesSorted = new List<SimilarityImages>();
var fileImage = new ComparableImage(singleFileInfo);
for (var i = 0; i < comparableImages.Count; i++)
{
if (exit)
return;
var destination = comparableImages[i];
var similarity = fileImage.CalculateSimilarity(destination);
var sim = new SimilarityImages(fileImage, destination, similarity);
similarityImagesSorted.Add(sim);
index++;
}
similarityImagesSorted.Sort();
similarityImagesSorted.Reverse();
similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);
var buttons =
new List<Button>
{
ScanBT
};
if (similarityImages[0].Similarity > 70)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
con.Open();
String getFile = "SELECT ImageName, Character FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
SqlCommand cmd2 = new SqlCommand(getFile, con);
SqlDataReader rd2 = cmd2.ExecuteReader();
while (rd2.Read())
{
for (int i = 0; i < 1; i++)
{
string getText = rd2["Character"].ToString();
Action showText = () => ocrTB.AppendText(getText);
ocrTB.Invoke(showText);
}
}
con.Close();
}
else
{
MessageBox.Show("No character found!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
i understand the reason it occur is that the image has been duplicated. But I have no idea how to solve it.
First off this looks like a dublicate of this topic:
c# Bitmap.Save A generic error occurred in GDI+ windows application
You also authored that question. From what I can tell it's the same question regarding the same code.
You mention this happens the second time you select an area, and both time you save the image to the same path. You also say the errors occurs when saving.
I think that would be a very strong indication of a permission error. Have you tried saving to a new file name every time as a test?
If it's a permission error then you simply need to dispose of any resources that have taken a lock on that file.
There are plenty of examples of this out there:
http://www.kerrywong.com/2007/11/15/understanding-a-generic-error-occurred-in-gdi-error/
public void Method1()
{
Image img = Image.FromFile(fileName);
Bitmap bmp = img as Bitmap;
Graphics g = Graphics.FromImage(bmp);
Bitmap bmpNew = new Bitmap(bmp);
g.DrawImage(bmpNew, new Point(0, 0));
g.Dispose();
bmp.Dispose();
img.Dispose();
//code to manipulate bmpNew goes here.
bmpNew.Save(fileName);
}
There could however be other issues. If you get the image from a stream, this stream needs to remain open until you're done with the image. (When you dispose of the image you'll automatically dispose of the stream.)
I can't see anything like that in the code you've posted though.
If you are using a 3rd party library for the OCR part, it could also have taken a lock on the resource.
A good place to read about this would be here:
http://support.microsoft.com/?id=814675
However from all you've said it simply sounds like there's a lock on the file you try to save to. So as mentioned above I would start off by simply trying to give the file a new name each time. If it doesn't work then you can start exploring other possibilities.
Quick and dirty example:
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic-" + Guid.NewGuid().ToString() + #".jpg");
You should try this before dismissing a permission issue.
I have the following method that loads in a blank template image, draws the relevant information on it and saves it to another file. I want to change this slightly to achieve the following:
load in the template image
draw the relevant information on it
print it
I don't want to save it, just print it out. Here's my existing method:
public static void GenerateCard(string recipient, string nominee, string reason, out string filename)
{
// Get a bitmap.
Bitmap bmp1 = new Bitmap("template.jpg");
Graphics graphicImage;
// Wrapped in a using statement to automatically take care of IDisposable and cleanup
using (graphicImage = Graphics.FromImage(bmp1))
{
ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
// Create an Encoder object based on the GUID
// for the Quality parameter category.
Encoder myEncoder = Encoder.Quality;
graphicImage.DrawString(recipient, new Font("Arial", 10, FontStyle.Regular), SystemBrushes.WindowText, new Point(480, 33));
graphicImage.DrawString(WordWrap(reason, 35), new Font("Arial", 10, FontStyle.Regular), SystemBrushes.WindowText, new Point(566, 53));
graphicImage.DrawString(nominee, new Font("Arial", 10, FontStyle.Regular), SystemBrushes.WindowText, new Point(492, 405));
graphicImage.DrawString(DateTime.Now.ToShortDateString(), new Font("Arial", 10, FontStyle.Regular), SystemBrushes.WindowText, new Point(490, 425));
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100L);
myEncoderParameters.Param[0] = myEncoderParameter;
filename = recipient + " - " + DateTime.Now.ToShortDateString().Replace("/", "-") + ".jpg";
bmp1.Save(filename, jgpEncoder, myEncoderParameters);
}
}
Hope you can help,
Brett
Just print it to the printer without saving
This is the most simple example I could come up with.
Bitmap b = new Bitmap(100, 100);
using (var g = Graphics.FromImage(b))
{
g.DrawString("Hello", this.Font, Brushes.Black, new PointF(0, 0));
}
PrintDocument pd = new PrintDocument();
pd.PrintPage += (object printSender, PrintPageEventArgs printE) =>
{
printE.Graphics.DrawImageUnscaled(b, new Point(0, 0));
};
PrintDialog dialog = new PrintDialog();
dialog.ShowDialog();
pd.PrinterSettings = dialog.PrinterSettings;
pd.Print();
When you use the PrintDocument class, you can print without needing to save the image.
var pd = new PrintDocument();
pd.PrintPage += pd_PrintPage;
pd.Print()
And in the pd_PrintPage eventhandler:
void pd_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics gr = e.Graphics;
//now you can draw on the gr object you received using some of the code you posted.
}
NOTE: Don't dispose the Graphics object you received in the eventhandler. This is done by the PrintDocument object itself...
Use the PrintPage event;
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) {
e.Graphics.DrawImage(image, 0, 0);
}