I use the following method to create some image.
My question is how I can display it in .cshtml page (MVC3)? Which Razor syntax I have to use?
public FileContentResult DisplayFont()
{
int fontSize = 12;
string fontName = "Arial";
System.Drawing.Font rectangleFont = new System.Drawing.Font(fontName, fontSize, FontStyle.Bold);
int height = 150;
int width = 250;
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Color backgroundColor = Color.White;
g.Clear(backgroundColor);
g.DrawString(fontName, rectangleFont,SystemBrushes.WindowText, new PointF(10, 40));
MemoryStream outputStream = new MemoryStream();
bitmap.Save(outputStream, ImageFormat.Jpeg);
byte[] byteArray = outputStream.ToArray();
g.Dispose();
bitmap.Dispose();
return new FileContentResult(byteArray, "image/jpeg");
}
You can render it using a normal HTML img tag, using the URL of your DisplayFont action:
<img src='#Url.Action("DisplayFont")' />
Related
I want to save my label Control, but I have no idea to save it.
I tried draw text in Graphics class, but I can't draw "even allocation".
Is there any good way?
public Label makeLabel(string text, double width, double height, FontFamily fontFamily, FontStyle fontStyle, FontStretch fontStretch)
{
var label = new Label();
label.Width = width;
label.Height = height;
label.FontFamily = fontFamily;
label.FontStyle = fontStyle;
label.FontStretch = fontStretch;
label.Content = text;
return label;
}
public void SavePicture(Label label)
{
var path = "label.png";
// I have no idea to save;
}
public void SavePicture(Label label)
{
var path = "label.png";
var width = label.Width;
var height = label.Height;
var viewBox = new Viewbox();
var renderTargetBitmap = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Pbgra32);
var pngBitmapEncoder = new PngBitmapEncoder();
viewBox.Child = label;
viewBox.Measure(new Size(width, height));
viewBox.Arrange(new Rect(0, 0, width, height));
viewBox.UpdateLayout();
renderTargetBitmap.Render(viewBox);
pngBitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
using (var fileStream = File.Create(path))
{
pngBitmapEncoder.Save(fileStream);
}
}
This works without having label displayed on screen.
void SavePicture(FrameworkElement el)
{
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)el.ActualWidth, (int)el.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(el);
using (FileStream stream = File.Create(#"label.png"))
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(stream);
}
}
But you can call this method only after the Label is displayed.
Generate an Image From Text
public Image DrawText(String text, Font font, Color textColor, Color backColor)
{
//first, create a dummy bitmap just to get a graphics object
Image img = new Bitmap(1, 1);
Graphics drawing = Graphics.FromImage(img);
//measure the string to see how big the image needs to be
SizeF textSize = drawing.MeasureString(text, font);
//free up the dummy image and old graphics object
img.Dispose();
drawing.Dispose();
//create a new image of the right size
img = new Bitmap((int)textSize.Width, (int)textSize.Height);
drawing = Graphics.FromImage(img);
//paint the background
drawing.Clear(backColor);
//create a brush for the text
Brush textBrush = new SolidBrush(textColor);
drawing.DrawString(text, font, textBrush, 0, 0);
drawing.Save();
textBrush.Dispose();
drawing.Dispose();
return img;
}
And Callback
Font font = new Font("Arial", 20, FontStyle.Bold);
Color color = Color.FromArgb(255, 0, 0); //Red
Color background = Color.Transparent; //None Color
Image img = DrawText("Hoàng Long", font, color, background);
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
Tried:How to generate an image from text on fly at runtime
Please help me
Disclaimer: this code will create a white background. Not an Transparent. To make it Transparent you need to change this
var image = DrawTextImage(TextForImage, font, Color.Black, Color.Transparent);
public class TextToImage
{
// main method you need to call.
public byte[] GetImageFromText(string TextForImage)
{
FontFamily fontFamily = new FontFamily("Arial");
Font font = new Font(fontFamily, 40.0f);
var image = DrawTextImage(TextForImage, font, Color.Black, Color.Transparent);
var imgData = ImageToByteArray(image);
return imgData;
}
// convert image to byte array
private byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
private Image DrawTextImage(String text, Font font, Color textColor, Color backColor)
{
return DrawTextImage(text, font, textColor, backColor, new Size(500, 500));
}
// create image
private Image DrawTextImage(String text, Font font, Color textColor, Color backColor, Size minSize)
{
//first, create a dummy bitmap just to get a graphics object
SizeF textSize;
using (Image img = new Bitmap(1, 1))
{
using (Graphics drawing = Graphics.FromImage(img))
{
//measure the string to see how big the image needs to be
textSize = drawing.MeasureString(text, font);
if (!minSize.IsEmpty)
{
textSize.Width = textSize.Width > minSize.Width ? textSize.Width : minSize.Width;
textSize.Height = textSize.Height > minSize.Height ? textSize.Height : minSize.Height;
}
}
}
//create a new image of the right size
//Image retImg = new Bitmap((int)textSize.Width, (int)textSize.Height);
Image retImg = new Bitmap(500, 500);
using (var drawing = Graphics.FromImage(retImg))
{
//paint the background
drawing.Clear(backColor);
//create a brush for the text
using (Brush textBrush = new SolidBrush(textColor))
{
drawing.TextRenderingHint = TextRenderingHint.AntiAlias;
RectangleF rectF1 = new RectangleF(10, 10, 490, 490);
drawing.DrawString(text, font, textBrush, rectF1);
drawing.Save();
}
}
return retImg;
}
}
I think above code is self explanatory. you just create an instance of this helper class and pass text param.
TextToImage textToImage = new TextToImage();
byte[] byteArr = textToImage.GetImageFromText("some text to create image out of it");
Hope this helps. :)
I have two List one is of string and the other is of PictureBox type. I want to take the values of List of type string and the convert it into the Barcode then save it to the List of type PictureBox.
I am doing it like this right now:
List<System.Windows.Forms.PictureBox> PictureBoxList = new List<System.Windows.Forms.PictureBox>();
List<string> SerialNumberList = new List<string>();
int SerialNumberStart = 0;
for(int i = 0; i < 10 ; i++)
{
SerialNumberStart++;
SerialNumberList.Add("S" + SerialNumberStart);
}
private void PrintButton_Click(object sender, EventArgs e)
{
for(int j =0 ; j < SerialNumberList.Count ; j++)
{
BarcodeLib.TYPE barcodetype1 = BarcodeLib.TYPE.CODE39;
BarcodeLib.Barcode bar1 = new BarcodeLib.Barcode();
bar1.IncludeLabel = true;
PictureBoxList[j].Image = bar1.Encode(barcodetype1 ,SerialNumberList[j]); // It gives me exception of Index out of range
PictureBoxList.Add(PictureBoxList[j]);
printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument1_PrintPage);
printDocument1.Print();
}
}
private void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Bitmap myBitmap1 = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(myBitmap1, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
e.Graphics.DrawImage(myBitmap1, 0, 0);
myBitmap1.Dispose();
}
My first question is that How can I convert the string into the PictureBox.
And then converting each item of the PictureBox to the Bitmap and then printing all of the bitmaps now the code only Prints one barcode
you want like this.. right?? see this is the representaion of the this string "S1253551" in 3of9 and plain text and finally as image right??
public Image stringToImage(string inputString)
{
string text = inputString.Trim();
Bitmap bmp = new Bitmap(1, 1);
//Set the font style of output image
Font font = new Font("Free 3 of 9", 25, FontStyle.Regular, GraphicsUnit.Pixel);
Font font2 = new Font("Arial", 15, FontStyle.Regular, GraphicsUnit.Pixel);
Graphics graphics = Graphics.FromImage(bmp);
int width = (int)graphics.MeasureString(text, font).Width;
int height = (int)graphics.MeasureString(text, font).Height;
int height2 = (int)graphics.MeasureString(text, font2).Height;
bmp = new Bitmap(bmp, new Size(width, height+height2));
graphics = Graphics.FromImage(bmp);
//Specify the background color of the image
graphics.Clear(Color.Cyan);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
//Specify the text, font, Text Color, X position and Y position of the image
graphics.DrawString(text, font, new SolidBrush(Color.Black), 0, 0);
graphics.DrawString(text, font2, new SolidBrush(Color.Black), 0, height);
graphics.Flush();
graphics.Dispose();
//if you want to save the image uncomment the below line.
//bmp.Save(#"d:\myimage.jpg", ImageFormat.Jpeg);
return bmp;
}
Remember you must have installed "free 3 of 9" font.
you pass the string "S1253551" and it generate the barcode and add the plain text at bottom and finally return it as image.
Its working code i have tried at my end. Enjoy. :)
Download the working code from here Download
mean you have string and you have converted it to barcode. finally we have a property in barcode which holds the value of string right?? now you want to display that string as image??
if so then refer the below code -
public Image stringToImage(string inputString)
{
string text = inputString.Trim();
Bitmap bmp = new Bitmap(1, 1);
//Set the font style of output image
Font font = new Font("Arial", 25, FontStyle.Regular, GraphicsUnit.Pixel);
Graphics graphics = Graphics.FromImage(bmp);
int width = (int)graphics.MeasureString(text, font).Width;
int height = (int)graphics.MeasureString(text, font).Height;
bmp = new Bitmap(bmp, new Size(width, height));
graphics = Graphics.FromImage(bmp);
//Specify the background color of the image
graphics.Clear(Color.Cyan);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
//Specify the text, font, Text Color, X position and Y position of the image
graphics.DrawString(text, font, new SolidBrush(Color.Black), 0, 0);
graphics.Flush();
graphics.Dispose();
//if you want to save the image uncomment the below line.
//bmp.Save(#"d:\myimage.jpg", ImageFormat.Jpeg);
return bmp;
}
I believe, if bar1.Encode actually has return type of Image, this lines in PrintButton_Click method :
PictureBoxList[j].Image = bar1.Encode(barcodetype1 ,SerialNumberList[j]); // It gives me exception of Index out of range
PictureBoxList.Add(PictureBoxList[j]);
should be like this :
var pictureBox = new PictureBox();
pictureBox.Image = bar1.Encode(barcodetype1 ,SerialNumberList[j]);
PictureBoxList.Add(pictureBox);
UPDATE :
To make it clear, my answer above meant PrintButton_Click should be as follow :
private void PrintButton_Click(object sender, EventArgs e)
{
for(int j =0 ; j < SerialNumberList.Count ; j++)
{
BarcodeLib.TYPE barcodetype1 = BarcodeLib.TYPE.CODE39;
BarcodeLib.Barcode bar1 = new BarcodeLib.Barcode();
bar1.IncludeLabel = true;
var pictureBox = new PictureBox();
pictureBox.Image = bar1.Encode(barcodetype1 ,SerialNumberList[j]);
PictureBoxList.Add(pictureBox);
printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument1_PrintPage);
printDocument1.Print();
}
}
I am using asp.net mvc3. I am making a bitmap using text by system.drawing. I want
to send that image from my controller to my view in VIEWDATA, but in my view I cannot parse VIEWDATA properly.
This is the controller code:
public ActionResult About( string agha)
{
agha = "asgdjhagsdjgajdga";
Color BackColor = Color.White;
String FontName = "Times New Roman";
int FontSize = 25;
int Height = 50;
int Width = 700;
Bitmap bitmap = new Bitmap(Width, Height);
Graphics graphics = Graphics.FromImage(bitmap);
Color color = Color.Gray; ;
Font font = new Font(FontName, FontSize);
SolidBrush BrushBackColor = new SolidBrush(BackColor);
Pen BorderPen = new Pen(color);
Rectangle displayRectangle = new Rectangle(new Point(0, 0), new Size(Width - 1, Height - 1));
graphics.FillRectangle(BrushBackColor, displayRectangle);
graphics.DrawRectangle(BorderPen, displayRectangle);
graphics.DrawString(agha,font,Brushes.Red, 0, 0);
ViewData["picture"] = bitmap;
return View( );
}
The view calling the viewdata looks like this
<img src="#ViewData["picture"]." />
I'd recommend you writing a custom action result to avoid polluting your controller action with completely useless and boring GDI+ infrastructure code:
public class ImageResult : ActionResult
{
private readonly string _agha;
public ImageResult(string agha)
{
_agha = agha;
}
public override void ExecuteResult(ControllerContext context)
{
Color BackColor = Color.White;
String FontName = "Times New Roman";
int FontSize = 25;
int Height = 50;
int Width = 700;
using (Bitmap bitmap = new Bitmap(Width, Height))
using (Graphics graphics = Graphics.FromImage(bitmap))
{
Color color = Color.Gray;
Font font = new Font(FontName, FontSize);
SolidBrush BrushBackColor = new SolidBrush(BackColor);
Pen BorderPen = new Pen(color);
Rectangle displayRectangle = new Rectangle(new Point(0, 0), new Size(Width - 1, Height - 1));
graphics.FillRectangle(BrushBackColor, displayRectangle);
graphics.DrawRectangle(BorderPen, displayRectangle);
graphics.DrawString(_agha, font, Brushes.Red, 0, 0);
context.HttpContext.Response.ContentType = "image/jpg";
bitmap.Save(context.HttpContext.Response.OutputStream, ImageFormat.Jpeg);
}
}
}
and then simply define a controller action that will return this custom action result:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Image(string agha)
{
return new ImageResult(agha);
}
}
and from within some view (~/Views/Home/Index.cshtml in my example) you could reference the action that will dynamically generate the image for you:
<img src="#Url.Action("Image", new { agha = "foo bar" })" alt="" />
Another possibility if you don't want to create an additional action to build the image is to use the Data URI scheme which basically allows you to embed the image as Base64 data directly into the HTML. One caveat with this is that not all browsers support it and ni addition to that it makes your HTML pages much larger.
If it doesn't need to be in the ViewData (not sure if you will be able to do it in the ViewData because each resource (image, flash, the page itself) has a ContentType that doesn't change in the current request.
However, you can try this in your controller:
public ActionResult GenerateImage() {
FileContentResult result;
using(var memStream = new System.IO.MemoryStream()) {
bitmap.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg);
result = this.File(memStream.GetBuffer(), "image/jpeg");
}
return result;
}
In your view, you need to call the Controller/Action:
<img src='#Url.Action("GenerateImage")' alt="" />
Have you tried ContentResult.
You can try something like following ( not verified)
public ContentResult GetImage()
{
var content = new ContentResult();
content.Content = "Image as String";
content.ContentType = "image/jpg";
return content;
}
public ContentResult GetImage()
{
var content = new ContentResult();
content.Content = "Image as String";
content.ContentType = "~image/jpg";
return content;
}
public ActionResult GenerateImage() {
FileContentResult result;
using(var memStream = new System.IO.MemoryStream()) {
bitmap.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg);
result = this.File(memStream.GetBuffer(), "image/jpeg");
}
return result;
}
I'm using mvc2 and I would like to use action in controller, for example ShowSmallImage) and when I type www.url.com/ShowSmallImage that in browser the output is an image.
I tried something like this:
public Bitmap CreateThumbnail()
{
Image img1 = Image.FromFile(#"C:...\Uploads\Photos\178.jpg");
int newWidth = 100;
int newHeight = 100;
double ratio = 0;
if (img1.Width > img1.Height)
{
ratio = img1.Width / (double)img1.Height;
newHeight = (int)(newHeight / ratio);
}
else
{
ratio = img1.Height / (double)img1.Width;
newWidth = (int)(newWidth / ratio);
}
//a holder for the result
Bitmap result = new Bitmap(newWidth, newHeight);
//use a graphics object to draw the resized image into the bitmap
using (Graphics graphics = Graphics.FromImage(result))
{
//set the resize quality modes to high quality
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//draw the image into the target bitmap
graphics.DrawImage(img1, 0, 0, result.Width, result.Height);
}
return result;
}
As a result I get only System.Drawing.Bitmap in browser. I suppose I need to set response/content type of the page but have no idea how to do it...
Thanks,
Ile
Create a fileresult and return the stream to the bitmap & set the content type:
private FileResult RenderImage()
{
MemoryStream stream = new MemoryStream();
var bitmap = CreateThumbnail();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
Byte[] bytes = stream.ToArray();
return File(bytes, "image/png");
}
In a controller, say ResourceController you could have an Action that returns a FileResult. Like so
public FileResult Thumbnail()
{
var bitmap = // Your method call which returns a Bitmap
var ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Png);
return new FileStreamResult(ms, "image/png");
}
Then you can call http://www.mysite.com/Resource/Thumbnail.