Image upload quality bad - c#

I have an application that uploads images to a database and then show them in a webpage by using a Handler. My problem is that the images are showing in a different quality and color than the original ones. I don't know what the problem is.
File = FileUpload1.PostedFile;
imgbin = new Byte[File.ContentLength];
File.InputStream.Read(imgbin, 0, File.ContentLength);
imagename = FileUpload1.FileName;
// Here the image size is defined --------------------
System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
UploadedImageWidth = UploadedImage.PhysicalDimension.Width;
UploadedImageHeight = UploadedImage.PhysicalDimension.Height;
//Resize Image
int compressWidth;
if (UploadedImageWidth >639)
{
compressWidth = 640;
}
else
{
compressWidth = Convert.ToInt32(UploadedImageWidth);
}
ResizeImage compressPicture = new ResizeImage();
imgbin = compressPicture.ResizeImageFile(imgbin, compressWidth);
System.Drawing.Image Image = System.Drawing.Image.FromStream(new MemoryStream(imgbin));
public class ResizeImage
{
public byte[] ResizeImageFile(byte[] imageFile, int targetSize) // Set targetSize to 1024
{
using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
{
Size newSize = CalculateDimensions(oldImage.Size, targetSize);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format64bppPArgb))
{
byte[] byteArray = new byte[0];
using (Graphics canvas = Graphics.FromImage(newImage))
{
canvas.Clear(Color.White);
canvas.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
canvas.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
int quality = 100;
ImageCodecInfo codec = RetrieveCodec("image/jpeg");
using (MemoryStream m = new MemoryStream())
{
using (EncoderParameters codeParams = new EncoderParameters())
{
using (EncoderParameter p = new EncoderParameter(Encoder.Quality, quality))
{
codeParams.Param[0] = p;
newImage.Save(m, codec, codeParams);
byteArray = m.ToArray();
}
}
}
return byteArray;
}
}
}
}
private ImageCodecInfo RetrieveCodec(string mimeType)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.MimeType == mimeType)
return codec;
}
return null;
}
public static Size CalculateDimensions(Size oldSize, int targetSize)
{
decimal ajusteTamaño;
Size newSize = new Size();
if (oldSize.Width > targetSize)
{
ajusteTamaño = oldSize.Width / Convert.ToDecimal(targetSize);
newSize.Width = (int)(oldSize.Width / ajusteTamaño);
newSize.Height = (int)(oldSize.Height / ajusteTamaño);
}
else
{
newSize.Width = oldSize.Width;
newSize.Height = oldSize.Height;
}
return newSize;
}
}

Related

Final image has smaller image after merging multiple images

I am trying to create a big final jpg image from 4 different jpg images. I noticed after adding images onto the final image, the size of the image changes.
The size of the image should remain the same on the final image too.
Ex- The galaxy image(dark sky) on the final image looks small, compared to the actual image.
Any help would be appreciated.
private void CombineImages()
{
string path1 = #"C:\temp\";
DirectoryInfo directory = new DirectoryInfo(path1);
//change the location to store the final image.
FileInfo[] files = directory.GetFiles();
string finalImage = #"C:\\images\\FinalImage3.jpg";
List<int> imageHeights = new List<int>();
List<int> imagewidths = new List<int>();
int nIndex = 0;
int width = 0;
int maxHeight = 0;
int totalHeight = 0;
bool odd = true;
bool firstRow = true;
//to get height and width to create final image
foreach (FileInfo file in files)
{
if (odd)
{
if (firstRow)
{
Image img = Image.FromFile(file.FullName);
firstRow = false;
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
odd = false;
}
else
{
Image img = Image.FromFile(file.FullName);
maxHeight = imageHeights.Max();
imagewidths.Add(width+100);
width = 0;
totalHeight = totalHeight + maxHeight+img.Height+100;
imageHeights.Clear();
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
odd = false;
}
}
else
{
Image img = Image.FromFile(file.FullName);
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
odd = true;
}
}
imageHeights.Sort();
Bitmap img3 = new Bitmap(imagewidths.Max(), totalHeight);
Graphics g = Graphics.FromImage(img3);
g.Clear(Color.Gainsboro);
imageHeights = new List<int>();
imagewidths = new List<int>();
nIndex = 0;
width = 0;
maxHeight = 0;
totalHeight = 0;
odd = true;
firstRow = true;
int imagewidth = 0;
//actual merging of images
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
if (odd)
{
if (firstRow)
{
g.DrawImage(img, 25, 25);
firstRow = false;
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
odd = false;
}
else
{
maxHeight = imageHeights.Max();
g.DrawImage(img, 25, maxHeight+50);
imagewidths.Add(width);
width = 0;
totalHeight = totalHeight + maxHeight + img.Height;
imageHeights.Clear();
imageHeights.Add(img.Height);
width += img.Width;
imagewidth = img.Width;
img.Dispose();
odd = false;
}
}
else
{
imageHeights.Add(img.Height);
g.DrawImage(img, width+50, maxHeight+50);
img.Dispose();
odd = true;
}
img.Dispose();
}
g.Dispose();
System.Drawing.Imaging.Encoder myEncoder =
System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
myEncoderParameters.Param[0] = myEncoderParameter;
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
img3.Save(finalImage, jpgEncoder, myEncoderParameters);
img3.Dispose();
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}

SetResolution does nothing when joining tiff images

I've been trying to adjust the resolution for a new tiff that gets created from a group of other tiffs. I would like to drop the resolution to 100x100 dpi. Everything with the join works properly but the resolution in the final tiff will always be what the resolution is of the files I am joining together (used 300x300 dpi images). I have tried using some suggestions (Set DPI value to Tiff Image in C#) for getting/setting the PropertyItems but that has failed as well. Using the join technique below, what would be the proper way to set the resolution of the final image to 100x100 dpi?
Thank you.
public byte[] JoinTiffImages(
List<byte[]> images)
{
var fPage = FrameDimension.Page;
var nearest =
System.Drawing
.Drawing2D
.InterpolationMode
.NearestNeighbor;
if (images.Count == 0)
{
throw new ImageConverterException(
"Could not join an empty set of images.");
}
else if (images.Count == 1)
{
return images[0];
}
else
{
using (var ms = new MemoryStream())
{
using (var masterBitmap =
(Bitmap)DrawingImage.FromStream(
new MemoryStream(images[0])))
{
//get the codec for tiff files
var info = GetTifCodecInfo();
var enc = Encoder.SaveFlag;
var ep = new EncoderParameters(2);
ep.Param[0] = new EncoderParameter(
enc,
(long)EncoderValue.MultiFrame);
ep.Param[1] = new EncoderParameter(
Encoder.Compression,
(long)TifCompression.ToEncoderValue());
masterBitmap.SetResolution(100.0f, 100.0f);
masterBitmap.Save(ms, info, ep);
//save the intermediate frames
ep.Param[0] = new EncoderParameter(
enc,
(long)EncoderValue.FrameDimensionPage);
for (int i = 1; i < images.Count; i++)
{
using (var nextImg = (Bitmap)DrawingImage.FromStream(
new MemoryStream(images[i])))
{
for (int x = 0;
x < nextImg.GetFrameCount(fPage);
x++)
{
nextImg.SetResolution(100.0f, 100.0f);
nextImg.SelectActiveFrame(fPage, x);
masterBitmap.SaveAdd(nextImg, ep);
}
}
}
ep.Param[0] =
new EncoderParameter(
enc,
(long)EncoderValue.Flush);
//close out the file.
masterBitmap.SaveAdd(ep);
return ms.ToArray();
}
}
}
}
Here is a code that creates a multi-page tif file from a list of images.
It sets the DPI both to the master and all parts according to an input paramter.
private void saveTiff_Click(List<Image> imgList, string saveName, int dpi)
{
//all kudos to : http://bobpowell.net/generating_multipage_tiffs.aspx
foreach (Image img in imgList) ((Bitmap)img).SetResolution(dpi, dpi);
System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;
Bitmap master = new Bitmap(imgList[0]);
master.SetResolution(dpi, dpi);
ImageCodecInfo info = null;
// lets hope we have an TIF encoder
foreach (ImageCodecInfo ice in ImageCodecInfo.GetImageEncoders())
if (ice.MimeType == "image/tiff") info = ice;
// one parameter: MultiFrame
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
master.Save(saveName, info, ep);
// one parameter: further frames
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
for (int i = 1; i < imgList.Count; i++) master.SaveAdd(imgList[i], ep);
// one parameter: flush
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
master.SaveAdd(ep);
}
I was able to resolve my issue with some help from the comments. This function will handle the resolution change without the image changing size.
public static byte[] JoinTiffImages(
List<byte[]> images,
float res)
{
var fPage = FrameDimension.Page;
var nearest =
System.Drawing
.Drawing2D
.InterpolationMode
.NearestNeighbor;
if (images.Count == 0)
{
throw new Exception(
"Could not join an empty set of images.");
}
else if (images.Count == 1)
{
return images[0];
}
else
{
var ms = new MemoryStream();
//get the codec for tiff files
var info = GetTifCodecInfo();
var ep = new EncoderParameters(2);
ep.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.SaveFlag,
(long)EncoderValue.MultiFrame);
ep.Param[1] = new EncoderParameter(
System.Drawing.Imaging.Encoder.Compression,
(long)EncoderValue.CompressionLZW);
using (var masterImg =
(Bitmap)System.Drawing.Image.FromStream(
new MemoryStream(images[0])))
{
using (var resizedMaster =
new Bitmap(
(int)(masterImg.Width *
(res /
masterImg.HorizontalResolution)),
(int)(masterImg.Height *
(res /
masterImg.VerticalResolution))))
{
resizedMaster.SetResolution(
res,
res);
using (var gr = Graphics.FromImage(resizedMaster))
{
gr.InterpolationMode = nearest;
gr.DrawImage(
masterImg,
new Rectangle(
0,
0,
resizedMaster.Width,
resizedMaster.Height),
0,
0,
masterImg.Width,
masterImg.Height,
GraphicsUnit.Pixel);
}
resizedMaster.Save(ms, info, ep);
//save the intermediate frames
ep.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.SaveFlag,
(long)EncoderValue.FrameDimensionPage);
for (int i = 1; i < images.Count; i++)
{
using (var nextImg =
(Bitmap)System.Drawing.Image.FromStream(
new MemoryStream(images[i])))
{
for (int x = 0;
x < nextImg.GetFrameCount(fPage);
x++)
{
nextImg.SelectActiveFrame(fPage, x);
using (var resizedNext =
new Bitmap(
(int)(nextImg.Width *
(res /
nextImg.HorizontalResolution)),
(int)(nextImg.Height *
(res /
nextImg.VerticalResolution))))
{
resizedNext.SetResolution(
res,
res);
using (var gr =
Graphics.FromImage(resizedNext))
{
gr.InterpolationMode = nearest;
gr.DrawImage(
nextImg,
new Rectangle(
0,
0,
resizedNext.Width,
resizedNext.Height),
0,
0,
nextImg.Width,
nextImg.Height,
GraphicsUnit.Pixel);
}
resizedMaster.SaveAdd(resizedNext, ep);
}
}
}
}
ep.Param[0] =
new EncoderParameter(
System.Drawing.Imaging.Encoder.SaveFlag,
(long)EncoderValue.Flush);
//close out the file.
resizedMaster.SaveAdd(ep);
}
return ms.ToArray();
}
}
}
private static ImageCodecInfo GetTifCodecInfo()
{
foreach (var ice in ImageCodecInfo.GetImageEncoders())
{
if (ice.MimeType == "image/tiff")
{
return ice;
}
}
return null;
}

Image resize without saving on disk

in asp.net i want to resize the image and display on some control but without saving on disk.
is there any free utility just like for clasic asp.
http://www.aspjpeg.com/livedemo.html
This Thumbnail class will do the job.
public class Thumbnail
{
private string _filePath;
private int _maxWidth = 120;
private int _maxHeight = 120;
public string MimeType;
public System.Drawing.Imaging.ImageFormat ImageFormat;
public byte[] ImageBytes;
public Thumbnail(string filePath, int maxWidth, int maxHeight)
{
_filePath = filePath;
_maxWidth = maxWidth;
_maxHeight = maxHeight;
MakeThumbnail();
}
private void MakeThumbnail()
{
using (Image img = new Bitmap(_filePath))
{
Size newSize = GenerateImageDimensions(img.Width, img.Height, _maxWidth, _maxHeight);
int imgWidth = newSize.Width;
int imgHeight = newSize.Height;
// create the thumbnail image
using (Image img2 =
img.GetThumbnailImage(imgWidth, imgHeight,
new Image.GetThumbnailImageAbort(Abort),
IntPtr.Zero))
{
using (Graphics g = Graphics.FromImage(img2)) // Create Graphics object from original Image
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
//BMP 0, JPEG 1 , GIF 2 , TIFF 3, PNG 4
System.Drawing.Imaging.ImageCodecInfo codec;
switch (Path.GetExtension(_filePath))
{
case ".gif":
codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[2];
ImageFormat = System.Drawing.Imaging.ImageFormat.Gif;
MimeType = "image/gif";
break;
case ".png":
codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[4];
ImageFormat = System.Drawing.Imaging.ImageFormat.Png;
MimeType = "image/png";
break;
default: //jpg
codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
MimeType = "image/jpg";
break;
}
//Set the parameters for defining the quality of the thumbnail... here it is set to 100%
System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
//Now draw the image on the instance of thumbnail Bitmap object
g.DrawImage(img, new Rectangle(0, 0, img2.Width, img2.Height));
MemoryStream ms = new MemoryStream();
img2.Save(ms, codec, eParams);
ImageBytes = new byte[ms.Length];
ImageBytes = ms.ToArray();
ms.Close();
ms.Dispose();
}
}
}
}
public static Size GenerateImageDimensions(int currW, int currH, int destW, int destH)
{
int imgWidth = currW;
int imgHeight = currH;
if (imgWidth > destW)
{
double rate = (double)imgWidth / (double)destW;
imgWidth = destW;
imgHeight = (int)(imgHeight / rate);
}
if (imgHeight > destH)
{
double rate = (double)imgHeight / (double)destH;
imgHeight = destH;
imgWidth = (int)(imgWidth / rate);
}
return new Size(imgWidth, imgHeight);
}
private bool Abort()
{
return false;
}
}
Using is simple, just put this on your page codebehind. Browser output will be resized image.
Thumbnail thm = new Thumbnail("c:\some_image.jpg", 300, 300);
Response.ContentType = thm.MimeType;
Response.BinaryWrite(thm.ImageBytes);
This is probably what you need:
http://imageresizing.net/

How to create thumbnail of video using C#

i found some articles, some projects to create thumbnail of a video, using ffmpeg.exe, expression encoder
but when i downloaded the projects they are not working...
i am not getting that weather ffmpeg.exe downloaded by having problem or the projects are not working.
if anybody has other sources from where i can see samples. please post it..
-thanks in advance
Here is the class to make thumbnail of
either video or mage using ffmpeg.exe
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace Pariwaar.Controller
{
public class imageResize
{
public byte[] ResizeFromByteArray(int MaxSideSize, Byte[] byteArrayIn, string fileName)
{
byte[] byteArray = null; // really make this an error gif
MemoryStream ms = new MemoryStream(byteArrayIn);
byteArray = this.ResizeFromStream(MaxSideSize, ms, fileName);
return byteArray;
}
/// <summary>
/// converts stream to bytearray for resized image
/// </summary>
/// <param name="MaxSideSize"></param>
/// <param name="Buffer"></param>
/// <returns></returns>
public byte[] ResizeFromStream(int MaxSideSize, Stream Buffer, string fileName)
{
byte[] byteArray = null; // really make this an error gif
try
{
Bitmap bitMap = new Bitmap(Buffer);
int intOldWidth = bitMap.Width;
int intOldHeight = bitMap.Height;
int intNewWidth;
int intNewHeight;
int intMaxSide;
if (intOldWidth >= intOldHeight)
{
intMaxSide = intOldWidth;
}
else
{
intMaxSide = intOldHeight;
}
if (intMaxSide > MaxSideSize)
{
//set new width and height
double dblCoef = MaxSideSize / (double)intMaxSide;
intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
}
else
{
intNewWidth = intOldWidth;
intNewHeight = intOldHeight;
}
Size ThumbNailSize = new Size(intNewWidth, intNewHeight);
System.Drawing.Image oImg = System.Drawing.Image.FromStream(Buffer);
System.Drawing.Image oThumbNail = new Bitmap(ThumbNailSize.Width, ThumbNailSize.Height);
Graphics oGraphic = Graphics.FromImage(oThumbNail);
oGraphic.CompositingQuality = CompositingQuality.HighQuality;
oGraphic.SmoothingMode = SmoothingMode.HighQuality;
oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle oRectangle = new Rectangle
(0, 0, ThumbNailSize.Width, ThumbNailSize.Height);
oGraphic.DrawImage(oImg, oRectangle);
MemoryStream ms = new MemoryStream();
oThumbNail.Save(ms, ImageFormat.Jpeg);
byteArray = new byte[ms.Length];
ms.Position = 0;
ms.Read(byteArray, 0, Convert.ToInt32(ms.Length));
oGraphic.Dispose();
oImg.Dispose();
ms.Close();
ms.Dispose();
}
catch (Exception)
{
int newSize = MaxSideSize - 20;
Bitmap bitMap = new Bitmap(newSize, newSize);
Graphics g = Graphics.FromImage(bitMap);
g.FillRectangle(new SolidBrush(Color.Gray), new Rectangle(0, 0, newSize, newSize));
Font font = new Font("Courier", 8);
SolidBrush solidBrush = new SolidBrush(Color.Red);
g.DrawString("Failed File", font, solidBrush, 10, 5);
g.DrawString(fileName, font, solidBrush, 10, 50);
MemoryStream ms = new MemoryStream();
bitMap.Save(ms, ImageFormat.Jpeg);
byteArray = new byte[ms.Length];
ms.Position = 0;
ms.Read(byteArray, 0, Convert.ToInt32(ms.Length));
ms.Close();
ms.Dispose();
bitMap.Dispose();
solidBrush.Dispose();
g.Dispose();
font.Dispose();
}
return byteArray;
}
/// <summary>
/// Saves the resized image to specified file name and path as JPEG
/// and also returns the bytearray for any other use you may need it for
/// </summary>
/// <param name="MaxSideSize"></param>
/// <param name="Buffer"></param>
/// <param name="fileName">No Extension</param>
/// <param name="filePath">Examples: "images/dir1/dir2" or "images" or "images/dir1"</param>
/// <returns></returns>
public byte[] SaveFromStream(int MaxSideSize, Stream Buffer, string ErrorMessage, string filePath, string ThumbnailPath)
{
byte[] byteArray = null; // really make this an error gif
try
{
Bitmap bitMap = new Bitmap(Buffer);
int intOldWidth = bitMap.Width;
int intOldHeight = bitMap.Height;
int intNewWidth;
int intNewHeight;
int intMaxSide;
if (intOldWidth >= intOldHeight)
{
intMaxSide = intOldWidth;
}
else
{
intMaxSide = intOldHeight;
}
if (intMaxSide > MaxSideSize)
{
//set new width and height
double dblCoef = MaxSideSize / (double)intMaxSide;
intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
}
else
{
intNewWidth = intOldWidth;
intNewHeight = intOldHeight;
}
Size ThumbNailSize = new Size(intNewWidth, intNewHeight);
System.Drawing.Image oImg = System.Drawing.Image.FromStream(Buffer);
System.Drawing.Image oThumbNail = new Bitmap(ThumbNailSize.Width, ThumbNailSize.Height);
Graphics oGraphic = Graphics.FromImage(oThumbNail);
oGraphic.CompositingQuality = CompositingQuality.HighQuality;
oGraphic.SmoothingMode = SmoothingMode.HighQuality;
oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle oRectangle = new Rectangle
(0, 0, ThumbNailSize.Width, ThumbNailSize.Height);
oGraphic.DrawImage(oImg, oRectangle);
//Save File
string newFileName = filePath;
oThumbNail.Save(newFileName, ImageFormat.Jpeg);
MemoryStream ms = new MemoryStream();
oThumbNail.Save(ms, ImageFormat.Jpeg);
//--- done by vrunda create thmbnail
System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
System.Drawing.Image thumbNailImg =oThumbNail.GetThumbnailImage(100, 100, dummyCallBack, IntPtr.Zero);
thumbNailImg.Save(ThumbnailPath, ImageFormat.Jpeg);
//----- done by vrunda
byteArray = new byte[ms.Length];
ms.Position = 0;
ms.Read(byteArray, 0, Convert.ToInt32(ms.Length));
oGraphic.Dispose();
oImg.Dispose();
ms.Close();
ms.Dispose();
}
catch (Exception)
{
int newSize = MaxSideSize - 20;
Bitmap bitMap = new Bitmap(newSize, newSize);
Graphics g = Graphics.FromImage(bitMap);
g.FillRectangle(new SolidBrush(Color.Gray), new Rectangle(0, 0, newSize, newSize));
Font font = new Font("Courier", 8);
SolidBrush solidBrush = new SolidBrush(Color.Red);
g.DrawString("Failed To Save File or Failed File ", font, solidBrush, 10, 5);
g.DrawString(ErrorMessage, font, solidBrush, 10, 50);
MemoryStream ms = new MemoryStream();
bitMap.Save(ms, ImageFormat.Jpeg);
byteArray = new byte[ms.Length];
ms.Position = 0;
ms.Read(byteArray, 0, Convert.ToInt32(ms.Length));
ms.Close();
ms.Dispose();
bitMap.Dispose();
solidBrush.Dispose();
g.Dispose();
font.Dispose();
}
return byteArray;
}
public bool ThumbnailCallback()
{
return false;
}
}
}
here is the link of working ffmpeg sample
http://www.codeproject.com/Articles/241399/Convert-Video-to-Flash-Video-flv-and-progressive-s
hopefully this might help you

Why does resizing a png image lose transparency?

I am trying to resize an image as follows. I return the resized image into byte[] so that I can store it in database. The transparency of png image is lost. Please help to make this better.
private byte[] GetThumbNail(string imageFile, Stream imageStream,
int imageLen)
{
try
{
Image.GetThumbnailImageAbort imageCallBack =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap getBitmap = new Bitmap(imageFile);
byte[] returnByte = new byte[imageLen];
Image getThumbnail = getBitmap.GetThumbnailImage(160, 59,
imageCallBack, IntPtr.Zero);
using (Graphics g = Graphics.FromImage(getThumbnail))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(getThumbnail, 0, 0, 160, 59);
}
using (MemoryStream ms = new MemoryStream())
{
getThumbnail.Save(ms, ImageFormat.Png);
getThumbnail.Save("test.png", ImageFormat.Png);
returnByte = ms.ToArray();
}
return returnByte;
}
catch (Exception)
{
throw;
}
}
Your code doesn't do quite what you think that it does...
You use the GetThumbnailImage to resize the image, then you draw the thumbnail image into itself which is rather pointless. You probably lose the transparency in the first step.
Create a blank bitmap instead, and resize the source image by drawing it on the blank bitmap.
private byte[] GetThumbNail(string imageFile) {
try {
byte[] result;
using (Image thumbnail = new Bitmap(160, 59)) {
using (Bitmap source = new Bitmap(imageFile)) {
using (Graphics g = Graphics.FromImage(thumbnail)) {
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(source, 0, 0, 160, 59);
}
}
using (MemoryStream ms = new MemoryStream()) {
thumbnail.Save(ms, ImageFormat.Png);
thumbnail.Save("test.png", ImageFormat.Png);
result = ms.ToArray();
}
}
return result;
} catch (Exception) {
throw;
}
}
(I removed some parameters that were never used for anything that had anything to do with the result, like the imageLen parameter that was only used to create a byte array that was never used.)
Try using the .MakeTransparent() call on your bitmap object.
May be you should do something like this because this thing worked for me:
String path = context.Server.MapPath("/images");
if (!path.EndsWith("\\"))
path += "\\";
path += "none.png";
Image img = CreateThumbnail(Image.FromFile(path));
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);
private System.Drawing.Image CreateThumbnail(System.Drawing.Image i)
{
int dWidth = i.Width;
int dHeight = i.Height;
int dMaxSize = 150;
if (dWidth > dMaxSize)
{
dHeight = (dHeight * dMaxSize) / dWidth;
dWidth = dMaxSize;
}
if (dHeight > dMaxSize)
{
dWidth = (dWidth * dMaxSize) / dHeight;
dHeight = dMaxSize;
}
return i.GetThumbnailImage(dWidth, dHeight, delegate() { return false; }, IntPtr.Zero);
}

Categories