Cropping an image from file and resaving in C# - 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/

Related

split image to multiple image from the bottom up

I have a picture I want to print, but it's too big for one page
so i have decided to split it into multiple images
i have tried a method, but now im using this (Talha Irfan answer)
i also tried the other solutions there but those didnt worked as well
(ex. bm.Clone(rec, bm.PixelFormat);)
and here's my code(this is on non-form class)
Bitmap bm = new Bitmap(frmPrint.Width, frmPrint.Height);
Rectangle rec = new Rectangle(0, 200, 576, 300);
Bitmap bitmap = cropImg(bm, rec);
frmPrint.DrawToBitmap(bitmap, rec);
frmPrint._img = bitmap;
frmPrint.setImage();
and setImage function(on some form)
public void setImage()
{
pictureBox3.BackgroundImage = _img;
this.ShowDialog();
}
and cropImg is the same as cropAtRect
the below shows the original image (on the left)
the wanted result in the blue rectangle
and the actual result on the right
PS
my actual image size is (height = 698, wifht = 576)
Edit - as suggested below
on non-form class
Rectangle cropRect = new Rectangle(0, 0, 576, 698);
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height, bm.PixelFormat);
frmPrint.setImage(bm, target, cropRect);
target.Dispose();
at form class
public void setImage(Bitmap src, Bitmap target, Rectangle cropRect)
{
pictureBox3.Visible = false;
using (Graphics g = Graphics.FromImage(target))
{
g.DrawImage(src, new Rectangle(pictureBox3.Location.X, pictureBox3.Location.Y, target.Width, target.Height),
cropRect,
GraphicsUnit.Pixel);
}
this.ShowDialog();
}
Control.DrawToBitmap will always try to draw the whole control or form and will always start at the top. The parameter:
targetBounds
Type: System.Drawing.Rectangle
The bounds within which the control is rendered.
as the name implies, sets the target, not the source rectangle. Hence the white space above your result.
Move the line before cropping with a rectangle that holds the full area, maybe like this:
DrawToBitmap(bm, ClientRectangle);
and then crop the lower part as before..
Note that the cropping trick from your link will not work for DrawToBitmap; using a rectangle with a negative offset will cause a parameter exception.
Btw: to safely dispose of a Bitmap in a PictureBox use this:
Bitmap dummy = (Bitmap )somePictureBox.Image;
somePictureBox.Image = null;
if (dummy != null) dummy.Dispose;
And, indeed, the answer by ChrisJJ in the link leaks the Graphics object.
Update:
Since you seem to have lost control over the various changes and suggestions, here is the minimal code change from the original post:
Bitmap bm = new Bitmap(frmPrint.ClientWidth, frmPrint.ClientHeight);
DrawToBitmap(bm, frmPrint.ClientRectangle);
Rectangle rec = new Rectangle(0, 200, 576, 300);
Bitmap bitmap = cropImg(bm, rec);
frmPrint._img = bitmap;
frmPrint.setImage();
With:
public void setImage()
{
Bitmap dummy = pictureBox3.BackgroundImage;
pictureBox3.BackgroundImage = null;
if (dummy != bnull) dummy.Dispose();
pictureBox3.BackgroundImage = _img;
this.ShowDialog();
}
In the cropImg function add a g.Dispose before returning.

Adding footer to image in C#

I am using GetUserMedia API to capture image and draw it to canvas. Using toDataURL() of canvas I get the "ImageUrl". The url is saved as png image to local file. What I am looking is that before saving the image add some comment about image at bottom of image(not over the image) like a footer. I have the below code. Can any one suggest me how to do this in c#.
imageByte= Convert.FromBase64String(ImageUrl);
using (var streamBitmap = new MemoryStream(imageByte))
{
using (var img = Image.FromStream(streamBitmap))
{
img.Save(localPath);
}
}
You can create new Bitmap which will be higher from the original image to fit also the footer below. Next copy the original image and footer to that bitmap and save the new bitmap.
The method to do would like this (assuming the footer width <= image width):
public Bitmap AppendImageFooter(System.Drawing.Image bmp, System.Drawing.Image footer)
{
//Create new image that will be bigger then original image to make place for footer
Bitmap newImage = new Bitmap(bmp.Height+footer.Height,bmp.Width);
//Get graphics from new Image and copy original image and next footer below
Graphics g = Graphics.FromImage(newImage);
g.DrawImage(bmp, new Point(0, 0));
g.DrawImage(footer, new Point(0, bmp.Height));
g.Dispose();
return newImage;
}
And you can fit it in your code at this place:
var footer = Image.FromFile("path_to_your_footer.png");
imageByte= Convert.FromBase64String(ImageUrl);
using (var streamBitmap = new MemoryStream(imageByte))
{
using (var img = Image.FromStream(streamBitmap))
{
var imageWithFooter = AppendImageFooter(img, footer);
imageWithFooter.Save(localPath);
}
}
Edited in reply to additional question from comments:
You can build the footer in runtime. Sample code below, of course you can draw whatever you like in whatever style you like:
public Bitmap AppendImageFooter(System.Drawing.Image bmp, string text)
{
//Create new image that will be bigger then original image to make place for footer
Bitmap newImage = new Bitmap(bmp.Height+200,bmp.Width);
//Get graphics and copy image and below the footer
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(bmp, new Point(0, 0));
g.FillRectangle(new SolidBrush(Color.Black), 0, bmp.Height, bmp.Width, 200);
g.DrawString(text, new Font("Arial", 14), new SolidBrush(Color.White), 20, bmp.Height + 20);
//Anything else you like, circles, rectangles, texts etc..
g.Dispose();
return newImage;
}
Here is the simplest way: I just created new image(footer), a new Image on which old image + footer image is drawn.
int footerHeight = 30;
Bitmap bitmapImg = new Bitmap(img);// Original Image
Bitmap bitmapComment = new Bitmap(img.Width, footerHeight);// Footer
Bitmap bitmapNewImage = new Bitmap(img.Width, img.Height + footerHeight);//New Image
Graphics graphicImage = Graphics.FromImage(bitmapNewImage);
graphicImage.Clear(Color.White);
graphicImage.DrawImage(bitmapImg, new Point(0, 0));
graphicImage.DrawImage(bitmapComment, new Point(bitmapComment.Width, 0));
graphicImage.DrawString("Hi, This is Vivek !", new Font("Arial", 15), new SolidBrush(Color.Black), 0, bitmapImg.Height + footerHeight / 6);
bitmapNewImage.Save(yourImagePath);
bitmapImg.Dispose();
bitmapComment.Dispose();
bitmapNewImage.Dispose();
'img' is the original Image.

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");
}

Size of image increases after cropping

I have c# code to crop images.
When i crop image (size:191 KB, using my c# code) then size of resulted (cropped) image increases (size:2.44 MB)
Please tell me why size increases after cropping ..???
Bitmap source = new Bitmap(#"F:\images\Row" + i + "Col" + j + ".jpg");
Rectangle section = new Rectangle(new Point(0, 0), new Size(1362, 761));
Bitmap CroppedImage = CropImage(source, section);
CroppedImage.Save(#"file path\Row" + i + "Col" + j + ".jpg");
public Bitmap CropImage(Bitmap source, Rectangle section)
{
// An empty bitmap which will hold the cropped image
Bitmap bmp = new Bitmap(section.Width, section.Height);
Graphics g = Graphics.FromImage(bmp);
// Draw the given area (section) of the source image
// at location 0,0 on the empty bitmap (bmp)
g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
return bmp;
}
Telepathic power: you are talking about size of file on disk and comparing original compressed file (likely JPG) with cropped version saved in non-compressed format (likely BMP).
Fix: save cropped image in compressed format.
Image.Save with 2 arguments lets you specify format (i.e. unlike one argument version you use in your sample).
Example from the article:
// Construct a bitmap from the button image resource.
Bitmap bmp1 = new Bitmap(typeof(Button), "Button.bmp");
// Save the image as a GIF.
bmp1.Save("c:\\button.gif", System.Drawing.Imaging.ImageFormat.Gif);

Save non-transparent image from a PictureBox with transparent images

I have a PictureBox with lots of transparent png's drawn into...
Now I'd like to save the content of this PictureBox to a file, but without the transparency.
How can I do this?
I have already tried to remove transparency from the Image like this, but it didn't work, I still got a transparent image after the save.
...
removeTransparency(pictureBox.Image).Save(saveFileDialog.FileName);
private Bitmap removeTransparency(Image transparentImage)
{
Bitmap src = new Bitmap(transparentImage);
Bitmap newImage = new Bitmap(src.Size.Width, src.Size.Height);
Graphics g = Graphics.FromImage(newImage);
g.DrawRectangle(new Pen(new SolidBrush(Color.White)), 0, 0, newImage.Width, newImage.Height);
g.DrawImage(src, 0, 0);
return newImage;
}
You may cycle through all pixel (please not using GetPixel/SetPixel) to change the color or you may create another bitmap with the same size, create a graphics context from the image, clear the image with your favorite background color and then draw your image on it (so transparent pixels simply will be replaced by the background color).
Example
Did you do something like this?
public static Bitmap Repaint(Bitmap source, Color backgroundColor)
{
Bitmap result = new Bitmap(source.Width, source.Height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(result))
{
g.Clear(backgroundColor);
g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height));
}
return result;
}

Categories

Resources