How to get BitmapSource from System.Drawing.Bitmap in C# 3.5

public BitmapSource getBitmapSourceFromBitmap(Bitmap bmp)

{

BitmapSource returnSource = null;

try

{

returnSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(),

IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

}

catch { returnSource = null; }

return returnSource;

}



...S.VinothkumaR.

Getting Bitmap from Base64String in C#

Use the following code for getting Bitmap from Base64String.

public Bitmap getBitmapFromBase64String(string base64Value)

{

Bitmap img = null;

byte[] imgData = Convert.FromBase64String(base64Value);

using (MemoryStream ms = new MemoryStream())

{

ms.Write(imgData, 0, imgData.Length);

img = (Bitmap)Image.FromStream(ms, true);

ms.Close();

ms.Dispose();

}

return img;

}


....S.VinothkumaR.

Displaying an Image in an aspx page as OutputStream using C#

Dear Viewers,

Here am going to give a solution to display an image in an aspx page as OutputStream by using c#.

First of all we need to remove all code in that aspx except the line of page tag (i.e., <%@ Page Language="C#")

In Page_Load

Do the code behind as follows,

Response.ContentType = "image/jpeg";
System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\test.jpg");
img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

Yes, this the way to save image in aspx page as OutputStream.

...S.VinothkumaR.

Getting Images from FTP using C#

Hi all,

Here the sample for getting an Image from ftp file path using C#.

using System.Net;

string path = "ftp://dev-ftp.test.com/" + folderName + "\\" + fileName;

FtpWebRequest ftp;

ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));

ftp.Credentials = new NetworkCredential(username, password);

ftp.Method = WebRequestMethods.Ftp.DownloadFile;

using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())

{

using (Stream responseStream = response.GetResponseStream())

{

using (FileStream fs = new FileStream(localPath+fileName, FileMode.Create))

{

byte[] buffer = new byte[102400];

int read = 0;

do

{

read = responseStream.Read(buffer, 0, buffer.Length);

fs.Write(buffer, 0, read);

fs.Flush();

} while (!(read == 0));

fs.Flush();

fs.Close();

response.Close();

responseStream.Close();


Hence we can save an image in to our local file path from ftp file path.

That's it....

...S.VinothkumaR.

Difference between <% %>, <%= %>, <%# %>?

Whenever we are going to write code inside the <% %> then that piece of code will treated as server side code generally vbscript.

When we are accessing any server side variable into the HTML (in .aspx) side then we use <%= %>.

When we are using any binding control like repeater, gridview… etc then to bind the particular column with the database value then we are using <%# %> when the Autogenerate column of the binding controls are FALSE

For Example:

Text='<%#Eval("FirstName") %>' this tag put inside the Text property of the control inside the datagrid like (textbox, label etc....)

...S.VinothkumaR.

Image Resizing by WPF: Using System.Windows.Media.Imaging;

Here is the example of getting resized image by using Imaging namespace in DotNet 3.0.

Same three reference need to add for resizing the image also. PresentationCore, WindowsBase and PresentationFramework.


private void ResizeImage(string SourceImagePath, string ImageType, string TargetImagePath, int decodePixelWidth, int decodePixelHeight)

{

newWidth = 0;

newHeight = 0;

getResizableHeightWidth(SourceImagePath, decodePixelWidth, decodePixelHeight);

byte[] imageBytes = LoadImageData(SourceImagePath);

ImageSource imageSource = CreateResizedImage(imageBytes, newWidth, newHeight);

imageBytes = GetEncodedImageData(imageSource, ImageType);

SaveImageData(imageBytes, TargetImagePath);

}

LoadImageData, GetEncodedImageData and SaveImageData methods are given in last post. Here the CreateResizedImage method is given in below.


//Method for getting resized image by given image data byte array with width and height.

ImageSource CreateResizedImage(byte[] imageData, int width, int height)

{

BitmapImage bmpImage = new BitmapImage();

bmpImage.BeginInit();

if (width > 0)

{

bmpImage.DecodePixelWidth = width;

}

if (height > 0)

{

bmpImage.DecodePixelHeight = height;

}

bmpImage.StreamSource = new MemoryStream(imageData);

bmpImage.CreateOptions = BitmapCreateOptions.None;

bmpImage.CacheOption = BitmapCacheOption.OnLoad;

bmpImage.EndInit();

Rect rect = new Rect(0, 0, width, height);

DrawingVisual drawingVisual = new DrawingVisual();

using (DrawingContext drawingContext = drawingVisual.RenderOpen())

{

drawingContext.DrawImage(bmpImage, rect);

}

RenderTargetBitmap resizedImage = new RenderTargetBitmap(

(int)rect.Width, (int)rect.Height, // Resized dimensions

96, 96, // Default DPI values

PixelFormats.Default); // Default pixel format

resizedImage.Render(drawingVisual);

return resizedImage;

}


//Method for getting resizable height and width by given height and width.

private void getResizableHeightWidth(string ImagePath, int maxWidth, int maxHeight)

{

System.Drawing.Image image = new Bitmap(ImagePath);

int width = image.Width;

int height = image.Height;

double widthFactor = (Convert.ToDouble(width) / Convert.ToDouble(maxWidth));

double heightFactor = (Convert.ToDouble(height) / Convert.ToDouble(maxHeight));

newWidth=0;

newHeight=0;

if (widthFactor > heightFactor)

{

newWidth = Convert.ToInt32(Convert.ToDouble(width) / widthFactor);

newHeight = Convert.ToInt32(Convert.ToDouble(height) / widthFactor);

}

else

{

newWidth = Convert.ToInt32(Convert.ToDouble(width) / heightFactor);

newHeight = Convert.ToInt32(Convert.ToDouble(height) / heightFactor);

}

if (newHeight == 0)

{

newHeight = 1;

}

if (newWidth == 0)

{

newWidth = 1;

}

}



That’s it.


...S.VinothkumaR.

Image Cropping by WPF: Using System.Windows.Media.Imaging;

Introducing System.Windows.Media.Imaging namespace provides types that are used to encode and decode bitmap images.


Here I am going to explain a sample application which is used to cropping images. Imaging namespace is in under Windows Presentation Foundation will do the image manipulation in simple manner.


First of all, we need to add the following reference in our project.

- PresentationCore

- PresentationFramework

- WindowsBase


Then use the following namespace,


using System.Windows.Media;

using System.Windows.Media.Imaging;


The method for creating crop images with passing appropriate parameters as follows,


//Method for Creating Crop Image

private void CreateCropImage(int x, int y, int width, int height, string SourceImagePath, string TargetImagePath, string ImageType)

{

byte[] imgBytest = LoadImageData(SourceImagePath);

System.Drawing.Image img=new Bitmap(SourceImagePath);

CroppedBitmap cb = new CroppedBitmap((BitmapSource)CreateImage(imgBytest,img.Width,img.Height), new Int32Rect(x, y, width, height));

ImageSource imageSource = cb;

byte[] imageBytes = GetEncodedImageData(imageSource, ImageType);

SaveImageData(imageBytes, TargetImagePath);

}


//Method for getting image bytes from image's source path by using FileStream.

private static byte[] LoadImageData(string filePath)

{

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

BinaryReader br = new BinaryReader(fs);

byte[] imageBytes = br.ReadBytes((int)fs.Length);

br.Close();

fs.Close();

return imageBytes;

}

//Method for getting cropped image.

private static ImageSource CreateImage(byte[] imageData, int decodePixelWidth, int decodePixelHeight)

{

if (imageData == null) return null;

BitmapImage result = new BitmapImage();

result.BeginInit();

if (decodePixelWidth > 0)

{

result.DecodePixelWidth = decodePixelWidth;

}

if (decodePixelHeight > 0)

{

result.DecodePixelHeight = decodePixelHeight;

}

result.StreamSource = new MemoryStream(imageData);

result.CreateOptions = BitmapCreateOptions.None;

result.CacheOption = BitmapCacheOption.OnLoad;

result.EndInit();

return result;

}


//Method for getting encoded image data for the cropped image.

internal byte[] GetEncodedImageData(ImageSource image, string preferredFormat)

{

byte[] returnData = null;

BitmapEncoder encoder = null;

switch (preferredFormat.ToLower())

{

case ".jpg":

case ".jpeg":

encoder = new JpegBitmapEncoder();

break;

case ".bmp":

encoder = new BmpBitmapEncoder();

break;

case ".png":

encoder = new PngBitmapEncoder();

break;

case ".tif":

case ".tiff":

encoder = new TiffBitmapEncoder();

break;

case ".gif":

encoder = new GifBitmapEncoder();

break;

case ".wmp":

encoder = new WmpBitmapEncoder();

break;

}

if (image is BitmapSource)

{

MemoryStream stream = new MemoryStream();

encoder.Frames.Add(BitmapFrame.Create(image as BitmapSource));

encoder.Save(stream);

stream.Seek(0, SeekOrigin.Begin);

returnData = new byte[stream.Length];

BinaryReader br = new BinaryReader(stream);

br.Read(returnData, 0, (int)stream.Length);

br.Close();

stream.Close();

}

return returnData;

}

//Method for saving the image data as image in to spec

private static void SaveImageData(byte[] imageData, string filePath)

{

FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);

BinaryWriter bw = new BinaryWriter(fs);

bw.Write(imageData);

bw.Close();

fs.Close();

}


That's it...


...S.VinothkumaR.