Extract text from image with particular height and width - c#

In that image particular height weight text need to be extract text. For that i used modiDocument. codes re below:
public string ExtractTextFromImage(string filepath)
{
try
{
Document modiDocument = new Document();
modiDocument.Create(filepath);
modiDocument.OCR(MiLANGUAGES.miLANG_ENGLISH);
MODI.Image modiImage = (modiDocument.Images[0] as MODI.Image);
string extractedText = modiImage.Layout.Text;
modiDocument.Close();
return extractedText;
}
catch (Exception)
{
throw;
}
return filepath;
}
From above code i can get fill text from image. how to take particular height width text from image.

Quote from https://stackoverflow.com/a/734941/3966756
You can use Graphics.DrawImage to draw a cropped image onto the graphics object from a bitmap.
Rectangle cropRect = new Rectangle(...);
Bitmap src = Image.FromFile(fileName) as Bitmap;
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
using(Graphics g = Graphics.FromImage(target))
{
g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height),
cropRect,
GraphicsUnit.Pixel);
}
Quote end
Using this Code for cropping the image you can only load the part of the Image you want to extract the text from.
Since i don't know if MODIDocuments support loading from a bitmap instead of a file you may need to write a temporary file somwhereon your filesystem.

Related

C# - Cannot save bitmap to file

recently I started working on my project and unfortunately I have a problem. I want to get sqaures 5x5 from one image, count average color of them and then draw a circle to another Bitmap so I can get a result like this http://imageshack.com/a/img924/9093/ldgQAd.jpg
I have it done, but I can't save to file the Graphics object. I've tried many solutions from Stack, but none of them worked for me.
My code:
//GET IMAGE OBJECT
Image img = Image.FromFile(path);
Image newbmp = new Bitmap(img.Width, img.Height);
Size size = img.Size;
//CREATE NEW BITMAP WITH THIS IMAGE
Bitmap bmp = new Bitmap(img);
//CREATE EMPTY BITMAP TO DRAW ON IT
Graphics g = Graphics.FromImage(newbmp);
//DRAWING...
//SAVING TO FILE
Bitmap save = new Bitmap(size.Width, size.Height, g);
g.Dispose();
save.Save("file.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
The file 'file.bmp' is just a blank image. What am I doing wrong?
First, your Graphics object should be created from the target bitmap.
Bitmap save = new Bitmap(size.Width, size.Height) ;
Graphics g = Graphics.FromImage(save );
Second, flush your graphics before Save()
g.Flush() ;
And last, Dispose() after Save() (or use a using block)
save.Save("file.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
g.Dispose();
It should give you something like this :
Image img = Image.FromFile(path);
Size size = img.Size;
//CREATE EMPTY BITMAP TO DRAW ON IT
using (Bitmap save = new Bitmap(size.Width, size.Height))
{
using (Graphics g = Graphics.FromImage(save))
{
//DRAWING...
//SAVING TO FILE
g.Flush();
save.Save("file.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
}
}

Save an image and text as one

I am currently making an MVC project where the User will receive a Certificate which is displayed on the page. The Certificate is an image and then Text is used to overlap the image where the Users name and other information will be printed, using css to format the text to the correct part of the image.
As the image and text are technically still separate, saving the image does not save the text on top so what you save is just the template of a certificate and no text.
Is there a way to save both image and text as one, as if the text was pressed onto the image and was the same object? If so, I would appreciate being pointed in the right direction to know how to do this. Any ideas or code to save an image and text as one it would be very helpful.
Thanks.
May this help you
private void makeCertificate(string name, string id, string otherDetails) //You can pass any other details as well
{
System.Drawing.Image PrePrintedCertificate;
name = name.ToUpper();
string PrePrintedCertificateName = "Certificate.jpg"; //Assuming Certificate JPG File is in the bin folder
using (FileStream stream = new FileStream(PrePrintedCertificateName, FileMode.Open, FileAccess.Read))
{
PrePrintedCertificate = System.Drawing.Image.FromStream(stream);
}
RectangleF rectf4Name = new RectangleF(655, 460, 535, 90); //rectf for Name
RectangleF rectf4ID = new RectangleF(655, 560, 400, 40);
System.Drawing.Rectangle rect;
Bitmap picEdit = new Bitmap(PrePrintedCertificate, new System.Drawing.Size(1241, 1756));
using (Graphics g = Graphics.FromImage(picEdit))
{
//g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Red, 2), 662, 530, 90, 40);
//I have used upper line to see where is my RectangleF creating on the image
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
StringFormat sf1 = new StringFormat();
sf1.Alignment = StringAlignment.Near;
//g.DrawImage(codeImage, rect); //If you wanted to draw another image on the certificate image
g.DrawString(name, new System.Drawing.Font("Thaoma", 26, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, rectf4Name, sf);
g.DrawString(Track.Text, new System.Drawing.Font("Thaoma", 14, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, rectf4ID, sf1);
}
try
{
if (File.Exists(id + ".jpg"))
File.Delete(id + ".jpg");
picEdit.Save(id + ".jpg", ImageFormat.Jpeg);
picEdit.Dispose();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
Things to note here is that this image is a A4 size paper image with portrait orientation. You probably need to change Bitmap picEdit = new Bitmap(PrePrintedCertificate, new System.Drawing.Size(1241, 1756)); to Bitmap picEdit = new Bitmap(PrePrintedCertificate, new System.Drawing.Size(1756,1241));
Another thing is the names and other details has been printed on the image with random place but you can see where exactly you wish to print the details.
You can look where it will get printed using g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Red, 2), 662, 530, 90, 40); the Parameters you gonna pass here will be same as the RectangleF Parameters.
Save the graphic as an SVG and add the text using a text object.
You can also use CSS within the SVG to style the text.
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<text x="20" y="40">Example SVG text 1</text>
</svg>

Adding dynamic text to image

I currently have an image which gets displayed to the user, I'm trying to add dynamic text to this image based on two parameters passed in.
The issue I have is when I step through the code it all seems to be working correctly, however when I see the image on the screen after the below code has run it doesn't have the text on it.
Below is my current set up of code:
public ActionResult GenerateImage(string savingAmount, string savingDest)
{
// Hardcoding values for testing purposes.
savingAmount = "25,000.00";
savingDest = "Canada";
PointF firstLocation = new PointF(10f, 10f);
PointF secondLocation = new PointF(10f, 50f);
Image imgBackground = Image.FromFile(Server.MapPath("~/assets/img/fb-share.jpg"));
int phWidth = imgBackground.Width; int phHeight = imgBackground.Height;
Bitmap bmBackground = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
bmBackground.SetResolution(72, 72);
Graphics grBackground = Graphics.FromImage(bmBackground);
Bitmap bmWatermark;
Graphics grWatermark;
bmWatermark = new Bitmap(bmBackground);
bmWatermark.SetResolution(imgBackground.HorizontalResolution, imgBackground.VerticalResolution);
grWatermark = Graphics.FromImage(bmWatermark);
grBackground.SmoothingMode = SmoothingMode.AntiAlias;
// Now add the dynamic text to image
using (Graphics graphics = Graphics.FromImage(imgBackground))
{
using (Font arialFont = new Font("Arial", 10))
{
grWatermark.DrawString(savingAmount, arialFont, Brushes.White, firstLocation);
grWatermark.DrawString(savingDest, arialFont, Brushes.White, secondLocation);
}
}
imgBackground.Save(Response.OutputStream, ImageFormat.Png);
Response.ContentType = "image/png";
Response.Flush();
Response.End();
return null;
}
As mentioned after this code has run, I then see the image in the browser however text is not displayed on the image, can anyone see / suggest what maybe causing this issue?
I feel like there are way to many images in that code for what you are describing as the intent of the code. What you want should reduce to this:
Load Image
Create Graphics on that Image
Draw into the Graphics and close
Output image to client
In the code sample you provided you are opening the Graphics on imgBackground then drawing into the grWatermark graphics which is opened earlier on against an image you never touch again.
public ActionResult GenerateImage(string savingAmount, string savingDest)
{
// Hardcoding values for testing purposes.
savingAmount = "25,000.00";
savingDest = "Canada";
PointF firstLocation = new PointF(10f, 10f);
PointF secondLocation = new PointF(10f, 50f);
Image imgBackground = Image.FromFile(Server.MapPath("~/assets/img/fb-share.jpg"));
using (Graphics graphics = Graphics.FromImage(imgBackground))
{
using (Font arialFont = new Font("Arial", 10))
{
graphics.DrawString(savingAmount, arialFont, Brushes.White, firstLocation);
graphics.DrawString(savingDest, arialFont, Brushes.White, secondLocation);
}
}
imgBackground.Save(Response.OutputStream, ImageFormat.Png);
Response.ContentType = "image/png";
Response.Flush();
Response.End();
return null;
}

Merging 2 images using C#

I want to merge two pictures in my C# program.
the first one is any picture in grayscale mode, and the second one is like in this picture:
Both of the pictures/images have the same size, and this is my code:
Bitmap first = new Bitmap (picturebox1.image);
Bitmap second = new Bitmap (picturebox2.image);
Bitmap result = new Bitmap (first.width, first.height);
Graphics g = Graphics.FromImage(result);
g.DrawImageUnscaled(first, 0, 0);
g.Flush();
g.DrawImageUnscaled(second, 0, 0);
g.Flush();
picturebox3.image = result;
I can join those picture, but the result has smaller size than the two originals (both pictures have same size). Could anyone give me some suggestions?
Additionally, I want the result picture has condition like this :
if the edge pixel in 2nd picture dropped to the bright side at the 1st one, it will be dark, otherwise when the edge dropped to the dark side, it will be bright (seem glow).
so the text will be semi transparent.
Here's an example of the results I want.
Could anyone give some suggestions please?
It was for joining
Bitmap first = new Bitmap (picturebox1.Image);
Bitmap second = new Bitmap (picturebox2.Image);
Bitmap result = new Bitmap (first.Width+first.Width, first.Height);
Graphics g = Graphics.FromImage(result);
g.DrawImageUnscaled(first, 0, 0);
g.DrawImageUnscaled(second,first.Width, 0);
Try this for merging one on top another . set alpha by yourself ( red: U can use BitMap.MakeTransParent if u not want alpha)
public Bitmap SetImageOpacity(Image image, float opacity)
{
try
{
//create a Bitmap the size of the image provided
Bitmap bmp = new Bitmap(image.Width, image.Height);
//create a graphics object from the image
using (Graphics gfx = Graphics.FromImage(bmp))
{
//create a color matrix object
ColorMatrix matrix = new ColorMatrix();
//set the opacity
matrix.Matrix33 = opacity;
//create image attributes
ImageAttributes attributes = new ImageAttributes();
//set the color(opacity) of the image
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
//now draw the image
gfx.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
}
return bmp;
}
catch (Exception ex)
{
return null;
}
}
private void button1_Click(object sender, EventArgs e)
{
Bitmap first = new Bitmap(pictureBox1.Image);
Bitmap second = SetImageOpacity(pictureBox2.Image, 0.5f);
//Bitmap result = new Bitmap(first.Width, first.Height);
//fix :
Bitmap result = new Bitmap(Math.Max(first.Width,second.Width), Math.Max(first.Height,second.Height));
Console.WriteLine(first.Width);
Graphics g = Graphics.FromImage(result);
g.DrawImageUnscaled(first, 0, 0);
g.DrawImageUnscaled(second, 0, 0);
pictureBox3.Image = result;
result.Save("result.jpg" );
}
}
}
And Coming For watermark why not you want to use Drawstring with alpha
here is article for all these http://www.codeproject.com/Articles/5034/How-to-implement-Alpha-blending
You need to include the System.Drawing.Imaging namespace to make this code work.
Go through following code:
private void CombineImages(FileInfo[] files)
{
//change the location to store the final image.
string finalImage = #"C:\\MyImages\\FinalImage.jpg";
List imageHeights = new List();
int nIndex = 0;
int width = 0;
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
}
imageHeights.Sort();
int height = imageHeights[imageHeights.Count - 1];
Bitmap img3 = new Bitmap(width, height);
Graphics g = Graphics.FromImage(img3);
g.Clear(SystemColors.AppWorkspace);
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
if (nIndex == 0)
{
g.DrawImage(img, new Point(0, 0));
nIndex++;
width = img.Width;
}
else
{
g.DrawImage(img, new Point(width, 0));
width += img.Width;
}
img.Dispose();
}
g.Dispose();
img3.Save(finalImage, System.Drawing.Imaging.ImageFormat.Jpeg);
img3.Dispose();
imageLocation.Image = Image.FromFile(finalImage);
}
Follow Link:
http://www.niteshluharuka.com/2012/08/combine-several-images-to-form-a-single-image-using-c/
This codeproject article shows how to watermark an image with text as well as another image.
In summary, what you have to do is draw your watermark image over the image with the desired transparency.

How to properly use Image as ToolTip?

I have a BitmapSource 1690x214 (taken from an EMF file using this code), and I want to use this image as ToolTip. This is the image displayed using Paint:
So i wrote this code:
BitmapSource bmp = myBitmapSource; // "Dk01Light.EMF"
Image img = new Image()
{
Source = bmp,
Width = bmp.Width,
Height = bmp.Height,
Stretch = Stretch.Uniform,
};
myTooltip = img;
And this is the result:
As you can see, the right and bottom margin are completly different. Why? How can i fix this problem?
It seems like a DPI issue. First try removing the Width and Height from your Image initializer. It should also-size to fit its content.
You can also try replacing the code you linked to with the following to make sure the image is being produced properly:
using (System.Drawing.Imaging.Metafile emf = new System.Drawing.Imaging.Metafile(path))
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(emf.Width, emf.Height))
{
bmp.SetResolution(emf.HorizontalResolution, emf.VerticalResolution);
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
{
g.DrawImage(emf,
new Rectangle(0, 0, emf.Width, emf.Height),
new Rectangle(0, 0, emf.Width, emf.Height),
GraphicsUnit.Pixel
);
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
}

Categories