Download generated bitmap image from ASP.NET website - c#

I'm dynamically generating image from text, and existing image on my asp.net website.
Here is the code:
string barcode = Request.QueryString["BarCode"];
int w = barcode.Length * 40;
// Create a bitmap object of the width that we calculated and height of 100
Bitmap oBitmap = new Bitmap(w, 50);
// then create a Graphic object for the bitmap we just created.
Graphics oGraphics = Graphics.FromImage(oBitmap);
// Now create a Font object for the Barcode Font
// (in this case the IDAutomationHC39M) of 18 point size
Font oFont = new Font("BarcodeFont", 12);
// Let's create the Point and Brushes for the barcode
PointF oPoint = new PointF(2f, 2f);
SolidBrush oBrushWrite = new SolidBrush(Color.Black);
SolidBrush oBrush = new SolidBrush(Color.White);
// Now lets create the actual barcode image
// with a rectangle filled with white color
oGraphics.FillRectangle(oBrush, 0, 0, w, 100);
// We have to put prefix and sufix of an asterisk (*),
// in order to be a valid barcode
oGraphics.DrawString(barcode, oFont, oBrushWrite, oPoint);
// Then we send the Graphics with the actual barcode
Response.ContentType = "image/png";
oBitmap.Save(Response.OutputStream, ImageFormat.Png);
As you can see the bitmap is saved and showed on aspx page after postback. What I wanna do is when user click Button1, then image is generated and browser download window pops up, without saving on server or showing on page. How to do this? Please help me.

You should update your response like following:
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition","attachment; filename=downloadedFile.JPG");
Response.TransmitFile( #"c:/my documents/images/file.xxx" );
Response.End();
For more Information: http://www.west-wind.com/weblog/posts/2007/May/21/Downloading-a-File-with-a-Save-As-Dialog-in-ASPNET

Related

Image and text gets distorted/blurred on form background

I tried this code, it print distorted image and text on black background of a desktop.
I am using a Form with a transparent background. I want to print image on the background.
this.TransparencyKey = BackColor;
Bitmap original = null;
original = new Bitmap(imagePath);
Bitmap newImage = new Bitmap(width, height + rect.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
var newGrp = Graphics.FromImage(newImage);
newGrp.Clear(Color.Transparent);
newGrp.InterpolationMode = InterpolationMode.HighQualityBilinear;
newGrp.SmoothingMode = SmoothingMode.HighQuality;
newGrp.TextRenderingHint = TextRenderingHint.AntiAlias;
newGrp.CompositingQuality = CompositingQuality.HighQuality;
newGrp.DrawImage(original, 0, rect.Height, width, height);
newGrp.DrawString(text, font, color, textStartPosition, 0);
this.BackgroundImage = (Image)newImage;
Original is bitmap from image file and color of text is gray.The form is transparent. The new image is painted as background of form. Depend on background color of desktop(dynamic color), I want to print image on form, But my concerns about text is not clear.
I expect clear image and text on black background.

Cropping an image from file and resaving in C#

Never really worked with Graphics before. I have looked around on this and pieced together a few solutions from answers which address small parts of my question. but none have worked.
I want to load an image from a file, which will always be 320x240 in size. I then want to crop it to obtain a 240x240 image, with the outer 40px on each side trimmed. After this is done I want to save as a new image.
private void croptoSquare(string date)
{
//Location of 320x240 image
string fileName = Server.MapPath("~/Content/images/" + date + "contactimage.jpg");
//New rectangle of final size (I think maybe Point is where I would eventually specify where the crop square site i.e. (40, 0))
Rectangle cropRect = new Rectangle(new Point(0, 0), new Size(240, 240));
//Create a Bitmap with correct height/width.
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
//Load image from file
using (Image image = Image.FromFile(fileName))
{
//Create Graphics object from image
using (Graphics graphic = Graphics.FromImage(image))
{
//Not sure what this does, I found it on a post.
graphic.DrawImage(image,
cropRect,
new Rectangle(0, 0, target.Width, target.Height),
GraphicsUnit.Pixel);
fileName = Server.MapPath("~/Content/images/" + date + "contactimagecropped.jpg");
image.Save(fileName);
}
}
}
Currently it is simply resaving the same image and I'm not sure why. I have specified a destination rectangle as 240x240 and a src rectangle as 320x240.
As I say I know basically nothing about working with graphics objects so I imagine this is blatant.
Can anybody tell me how to achieve what I want?
private void croptoSquare(string date)
{
//Location of 320x240 image
string fileName = Server.MapPath("~/Content/images/" + date + "contactimage.jpg");
// Create a new image at the cropped size
Bitmap cropped = new Bitmap(240,240);
//Load image from file
using (Image image = Image.FromFile(fileName))
{
// Create a Graphics object to do the drawing, *with the new bitmap as the target*
using (Graphics g = Graphics.FromImage(cropped) )
{
// Draw the desired area of the original into the graphics object
g.DrawImage(image, new Rectangle(0, 0, 240, 240), new Rectangle(40, 0, 240, 240), GraphicsUnit.Pixel);
fileName = Server.MapPath("~/Content/images/" + date + "contactimagecropped.jpg");
// Save the result
cropped.Save(fileName);
}
}
}
Why don't you use JCrop instead? http://www.programmerclubhouse.com/index.php/crop-image-using-jcrop-in-asp-net-c-shar/

Apply Curl effect to a static Image C#

Anyone ever wrote a C# GDI+ function to curl the corner of a BITMAP. I need to be able to take a static image and apply the peel effect to it on the bottom right corner. And I need to do it with C# all my searching leads to CSS3/FLASH/SilverLight virtual book type examples. I just want to create a static image that has a curled up corner and save the file.
Any Ideas?
Ok so I made the image with photo shop so that I can show you what I am trying to achieve
I start this image
and I want to write some C# code that would yield this image
The end result is just an image that is not animated, and does nothing. Any thoughts.
There are some good tools to do this, such as Fred's ImageMagick plugin script, but here is a C# version as requested.
using System.Drawing.Imaging;
public partial class ImagePeelEffect : Form
{
string WorkingDirectory = #"C:\temp\";
public ImagePeelEffect()
{
InitializeComponent();
}
private void ImagePeelEffect_Load(object sender, EventArgs e)
{
picBefore.Image = Image.FromFile(WorkingDirectory + "\\before.jpg");
}
private void button1_Click(object sender, EventArgs e)
{
//create a image object containing the photograph to add page peel effect
Image imgPhoto = Image.FromFile(WorkingDirectory + "\\before.jpg");
int phWidth = imgPhoto.Width;
int phHeight = imgPhoto.Height;
//create a Bitmap the Size of the original photograph
Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
//load the Bitmap into a Graphics object
Graphics grPhoto = Graphics.FromImage(bmPhoto);
//create a image object containing the PagePeel
Image imgPagePeel = new Bitmap(WorkingDirectory + "\\PagePeel.bmp");
int ppWidth = imgPagePeel.Width;
int ppHeight = imgPagePeel.Height;
//Set the rendering quality for this Graphics object
grPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
//Draws the photo Image object at original size to the graphics object.
grPhoto.DrawImage(
imgPhoto, // Photo Image object
new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
0, // x-coordinate of the portion of the source image to draw.
0, // y-coordinate of the portion of the source image to draw.
phWidth, // Width of the portion of the source image to draw.
phHeight, // Height of the portion of the source image to draw.
GraphicsUnit.Pixel); // Units of measure
//The first step in manipulating the PagePeel image is to replace
//the background color with one that is transparent (Alpha=0, R=0, G=0, B=0)
//to do this we will use a Colormap and define ImageAttributes with a RemapTable
ImageAttributes imageAttributes = new ImageAttributes();
ColorMap colorMap = new ColorMap();
//My PagePeel was defined with a background of 100% Green this will
//be the color we search for and replace with transparency
colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
//Set the Remap Table with the old and new color map
ColorMap[] remapTable = { colorMap };
imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
//For this example we will place the PagePeel in the bottom right
//hand corner of the photograph
int xPosOfPp = phWidth - ppWidth;
int yPosOfPp = phHeight - ppHeight + 1;
grPhoto.DrawImage(imgPagePeel,
new Rectangle(xPosOfPp, yPosOfPp, ppWidth, ppHeight), //Set the detination Position
0, // x-coordinate of the portion of the source image to draw.
0, // y-coordinate of the portion of the source image to draw.
ppWidth, // PagePeel Width
ppHeight, // PagePeel Height
GraphicsUnit.Pixel, // Unit of measurment
imageAttributes); //ImageAttributes Object
//Replace the original photgraphs bitmap with the new Bitmap
imgPhoto = bmPhoto;
grPhoto.Dispose();
//save new image to file system.
imgPhoto.Save(WorkingDirectory + "\\after.jpg", ImageFormat.Jpeg);
imgPhoto.Dispose();
imgPagePeel.Dispose();
//Show the After image
picAfter.Image = Image.FromFile(WorkingDirectory + "\\after.jpg");
}
The PagePeel.bmp:
The Before and After result:
Update
Here's a version that uses a Transparent Page Peel overlay so you dont neet to convert the "green screen" to invisible. The advantage of this method is when the original photograph contains the colour green RGB(0,255,0) it wont be turned into transparent:
TransparentPagePeel.png:
private void button2_Click(object sender, EventArgs e)
{
//create a image object containing the photograph to add page peel effect
Image imgPhoto = Image.FromFile(WorkingDirectory + "\\before.jpg");
int phWidth = imgPhoto.Width;
int phHeight = imgPhoto.Height;
//create a Bitmap the Size of the original photograph
Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
//load the Bitmap into a Graphics object
Graphics grPhoto = Graphics.FromImage(bmPhoto);
//create a image object containing the PagePeel
Image imgPagePeel = new Bitmap(WorkingDirectory + "\\transparentPagePeel.png");
int ppWidth = imgPagePeel.Width;
int ppHeight = imgPagePeel.Height;
//Set the rendering quality for this Graphics object
grPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
//Draws the photo Image object at original size to the graphics object.
grPhoto.DrawImage(
imgPhoto, // Photo Image object
new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
0, // x-coordinate of the portion of the source image to draw.
0, // y-coordinate of the portion of the source image to draw.
phWidth, // Width of the portion of the source image to draw.
phHeight, // Height of the portion of the source image to draw.
GraphicsUnit.Pixel); // Units of measure
//For this example we will place the PagePeel in the bottom right
//hand corner of the photograph
int xPosOfPp = phWidth - ppWidth;
int yPosOfPp = phHeight - ppHeight + 1;
grPhoto.DrawImage(imgPagePeel,
new Rectangle(xPosOfPp, yPosOfPp, ppWidth, ppHeight), //Set the detination Position
0, // x-coordinate of the portion of the source image to draw.
0, // y-coordinate of the portion of the source image to draw.
ppWidth, // PagePeel Width
ppHeight, // PagePeel Height
GraphicsUnit.Pixel, // Unit of measurment
null); //ImageAttributes Object
//Replace the original photgraphs bitmap with the new Bitmap
imgPhoto = bmPhoto;
grPhoto.Dispose();
//save new image to file system.
imgPhoto.Save(WorkingDirectory + "\\after1.jpg", ImageFormat.Jpeg);
imgPhoto.Dispose();
imgPagePeel.Dispose();
picAfter.Image = Image.FromFile(WorkingDirectory + "\\after1.jpg");
}

Created image from text cannot be displayed?

I have converted text to Image(.png) using ASP.NET C# in Visual Studio 2010. But the image created cannot be displayed in the browser after submitting and it shows an message
The image "http://localhost:49670/WebSite1/Default.aspx" cannot be displayed, because it contains errors.
During debugging there is no error or warning or anything like that. How can I resolve this?
Looking at the Url there is a chance that you are rendering image intermixed with HTML content...
Using ASHX is better option to render images - check out http://aspalliance.com/1322_Displaying_Images_in_ASPNET_Using_HttpHandlers.all
Try this....
private Bitmap CreateBitmapImage(string sImageText)
{
Bitmap objBmpImage = new Bitmap(1, 1);
int intWidth = 0;
int intHeight = 0;
// Create the Font object for the image text drawing.
Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
// Create a graphics object to measure the text's width and height.
Graphics objGraphics = Graphics.FromImage(objBmpImage);
// This is where the bitmap size is determined.
intWidth = (int)objGraphics.MeasureString(sImageText, objFont).Width;
intHeight = (int)objGraphics.MeasureString(sImageText, objFont).Height;
// Create the bmpImage again with the correct size for the text and font.
objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));
// Add the colors to the new bitmap.
objGraphics = Graphics.FromImage(objBmpImage);
// Set Background color
objGraphics.Clear(Color.White);
objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
objGraphics.DrawString(sImageText, objFont, new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);
objGraphics.Flush();
return (objBmpImage);
}

Remove Text from below of the BarCode in ASP.NET(C#)

I am generating the barcode generation of barcode is working fine barcode also read it perfectly.followin is the code for barcode generation:
private void GenerateBarCode(string codeInfo)
{
//Settings for the Image
string TypeFaceName = "IDAutomationHC39M";
string imageLocation = Server.MapPath("2010.png");
//The format of the image file
ImageFormat format = ImageFormat.Png;
//path of unique file name
string path = "D://MyProjects//RepeaterPaging//images//vijendra.png";
//REFERENCING A FONT
PrivateFontCollection fnts = new PrivateFontCollection();
fnts.AddFontFile("IDAutomationHC39M.ttf");
FontFamily fntfam = new FontFamily(TypeFaceName);
Font fnt = new Font(fntfam, 13);
fnts.AddFontFile("Arial.ttf");
FontFamily fntfam2 = new FontFamily("Arial", fnts);
//DRAWING THE IMAGE
Bitmap bmp = new Bitmap(960, 386); //Canvas size
Graphics g = Graphics.FromImage(bmp);
Bitmap orignBitmap = new Bitmap(imageLocation);
g.Clear(Color.Transparent); //Background color
SizeF bc = g.MeasureString(codeInfo, fnt);
Brush br = new SolidBrush(Color.Black);
g.DrawImage(orignBitmap, 10, 8);
g.DrawString(codeInfo, fnt, br, 585, 170); //Drawing the Image
g.TextRenderingHint=
bmp.Save(path, format); //Saving the Image file
bmp.Dispose(); //Releasing all resources (Image file)
Response.Clear();
}
alt text http://www.freeimagehosting.net/uploads/0e033f305b.png
Now I want to remove the text which is below of the barcode.
how can I do this?.
You can set Font = null; to remove text below barcode.
Barcode128 code128 = new Barcode128();
code128.CodeType = Barcode.CODE128;
code128.Code = "123456789";
code128.Font = null;
A better alternative might be to just use a font that doesn't have the text in the first place:
Try something like: Free Barcode Font - Code 39
You are creating the barcode using a font and the charcters under the bars are part of that font.
The only way to remove them would be to modify the bitmap (or crop it) after rendering the text; which requires knowing how big the final barcode is. Not impossible to do but a pain.

Categories

Resources