Thursday, December 9, 2010

Creating and merging two Images in C#

//Creating new Image
var bitmap1 = new Bitmap(1, 1);
var font = new Font("Arial", 25);
Graphics graphics = Graphics.FromImage(bitmap1);
int width1 = (int)graphics.MeasureString("hello world this is custome image", font).Width;
int height1 = (int)graphics.MeasureString("hello world this is custome image", font).Height;
bitmap1 = new Bitmap(bitmap1, new Size(width1, height1));
graphics = Graphics.FromImage(bitmap1);
graphics.Clear(Color.Gray);
graphics.DrawString("hello world this is custome image", font, new SolidBrush(Color.DarkGray), 0, 0);
graphics.Flush();

//accessing existing Image
var fileStream = new FileStream(Server.MapPath("//images//sky.jpg"), FileMode.Open);
var bytes1 = new byte[fileStream.Length];
fileStream.Read(bytes1, 0, bytes1.Length);
fileStream.Close();
var bitmap3 = new Bitmap(new MemoryStream(bytes1));

int width = bitmap3.Width;
int height = bitmap3.Height + height1;
var finalImage = new Bitmap(width, height);

//merging two images
//get a graphics object from the image so we can draw on it

var images = new List{bitmap3,bitmap1};
using (graphics = Graphics.FromImage(finalImage))
{
//set background color
graphics.Clear(Color.Transparent);

//go through each image and draw it on the final image
int offset = 0;
foreach (Bitmap image in images)
{
graphics.DrawImage(image,
new Rectangle(0, offset, image.Width, image.Height));
offset += image.Height;
}
}

// save on memory
var memoryStream = new MemoryStream();
finalImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] bytes = memoryStream.ToArray();

// throwing on web
HttpContext.Current.Response.ContentType = "image/jpeg";
HttpContext.Current.Response.Expires = 0;
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.End();

Wednesday, December 8, 2010

Rotate any control in silverlight

Rotate any control in silverlight

var messageTextBlock = new TextBlock
{
Text = "Messages",
Margin = new Thickness(5,20,0,0),
//FontWeight = FontWeights.Bold,
Foreground = new SolidColorBrush(Colors.White),
VerticalAlignment = VerticalAlignment.Top,
Width = 70,
Height=20,
TextWrapping = TextWrapping.Wrap,
};
RotateTransform r = new RotateTransform();
messageTextBlock.RenderTransform = r;
r.CenterX = 0;
r.CenterY = 0;
r.Angle = 90;