Rectangle cropRect = new Rectangle(...);
using (Bitmap src = Image.FromFile("") as Bitmap)
{
using (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);
}
}
}
var filename = @"c:\personal\images\horizon.png";
var img = Image.FromFile(filename);
var rect = new Rectangle(new Point(0, 0), img.Size);
var cloned = new Bitmap(img).Clone(rect, img.PixelFormat);
var bitmap = new Bitmap(cloned, new Size(50, 50));
cloned.Dispose();
var crop = new Rectangle(0, y, bitmap.Width, h);
var bmp = new Bitmap(bitmap.Width, h);
var tempfile = Application.StartupPath+"\\"+"TEMP"+"\\"+Path.GetRandomFileName();
using (var gr = Graphics.FromImage(bmp))
{
try
{
var dest = new Rectangle(0, 0, bitmap.Width, h);
gr.DrawImage(image,dest , crop, GraphicsUnit.Point);
bmp.Save(tempfile,ImageFormat.Jpeg);
bmp.Dispose();
}
catch (Exception)
{
}
}
// content of the Texture class
public class Texture
{
//name of the texture
public string name { get; set; }
//x position of the texture in the atlas image
public int x { get; set; }
//y position of the texture in the atlas image
public int y { get; set; }
//width of the texture in the atlas image
public int width { get; set; }
//height of the texture in the atlas image
public int height { get; set; }
}
Bitmap atlasImage = new Bitmap(@"C:\somepicture.png");
PixelFormat pixelFormat = atlasImage.PixelFormat;
foreach (Texture t in textureList)
{
try
{
CroppedImage = new Bitmap(t.width, t.height, pixelFormat);
// copy pixels over to avoid antialiasing or any other side effects of drawing
// the subimages to the output image using Graphics
for (int x = 0; x < t.width; x++)
for (int y = 0; y < t.height; y++)
CroppedImage.SetPixel(x, y, atlasImage.GetPixel(t.x + x, t.y + y));
CroppedImage.Save(Path.Combine(workingFolder, t.name + ".png"), ImageFormat.Png);
}
catch (Exception ex)
{
// handle the exception
}
}