I'm using SharpAvi .dll to convert a serie of images to video, everything looks fine, but when I try to play the video in windows media player I only get a black screen for one second, nothing else.
This is the code I wrote, (frames is a list of images as base64)
private void CreateMovie(List<string> frames)
{
int width = 320;
int height = 240;
var framRate = 2;
var writer = new AviWriter("C:\\test.avi")
{
FramesPerSecond = framRate,
EmitIndex1 = true
};
var stream = writer.AddVideoStream();
stream.Width = width;
stream.Height = height;
stream.Codec = KnownFourCCs.Codecs.DivX;
stream.BitsPerPixel = BitsPerPixel.Bpp32;
foreach (var frame in frames)
{
byte[] arr = Convert.FromBase64String(frame);
stream.WriteFrame(true, arr, 0, arr.Length);
}
writer.Close();
}
I can't see what the error could be. Does anyone have an idea?
So, i've found the errors:
the line:
stream.Codec = KnownFourCCs.Codecs.DivX;
should be:
stream.Codec = KnownFourCCs.Codecs.Uncompressed;
and all the frames of the video should be the same size as video, in order to do that i've use this block of code:
foreach (var frame in frames)
{
byte[] arr = Convert.FromBase64String(frame);
var bm = ToBitmap(arr);
var rbm = ReduceBitmap(bm, 320, 240);
byte[] fr = BitmapToByteArray(rbm);
stream.WriteFrame(true, fr, 0, fr.Length);
}
and here the helper functions:
public Bitmap ToBitmap(byte[] byteArrayIn)
{
var ms = new MemoryStream(byteArrayIn);
var returnImage = Image.FromStream(ms);
var bitmap = new Bitmap(returnImage);
return bitmap;
}
public Bitmap ReduceBitmap(Bitmap original, int reducedWidth, int reducedHeight)
{
var reduced = new Bitmap(reducedWidth, reducedHeight);
using (var dc = Graphics.FromImage(reduced))
{
dc.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
dc.DrawImage(original, new Rectangle(0, 0, reducedWidth, reducedHeight), new Rectangle(0, 0, original.Width, original.Height), GraphicsUnit.Pixel);
}
return reduced;
}
public static byte[] BitmapToByteArray(Bitmap bitmap)
{
BitmapData bmpdata = null;
try
{
bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
int numbytes = bmpdata.Stride * bitmap.Height;
byte[] bytedata = new byte[numbytes];
IntPtr ptr = bmpdata.Scan0;
Marshal.Copy(ptr, bytedata, 0, numbytes);
return bytedata;
}
finally
{
if (bmpdata != null)
{
bitmap.UnlockBits(bmpdata);
}
}
}
Related
I wrote the following methods,
public static byte[] BitmapToByteArray(Bitmap image)
{
byte[] returns = null;
if (image.PixelFormat == PixelFormat.Format8bppIndexed)
{
BitmapData bitmapData = image.LockBits(
new Rectangle(0, 0, image.Width, image.Height),
ImageLockMode.ReadWrite,
image.PixelFormat);
int noOfPixels = image.Width * image.Height;
int colorDepth = Bitmap.GetPixelFormatSize(image.PixelFormat);
int step = colorDepth / 8;
byte[] bytes = new byte[noOfPixels * step];
IntPtr address = bitmapData.Scan0;
Marshal.Copy(address, bytes, 0, bytes.Length);
////////////////////////////////////////////////
///
returns = (byte[])bytes.Clone();
///
////////////////////////////////////////////////
Marshal.Copy(bytes, 0, address, bytes.Length);
image.UnlockBits(bitmapData);
}
else
{
throw new Exception("8bpp indexed image required");
}
return returns;
}
And,
public static Bitmap ByteArrayToBitmap(byte[] bytes, int width, int height, PixelFormat pixelFormat)
{
Bitmap bitmap = new Bitmap(width, height, pixelFormat);
BitmapData bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
int colorDepth = Bitmap.GetPixelFormatSize(pixelFormat);
int noOfChannels = colorDepth / 8;
IntPtr address = bitmapData.Scan0;
//////////////////////////////////////////////////////////////
//
Marshal.Copy(bytes, 0, address, width * height * noOfChannels);
//
//////////////////////////////////////////////////////////////
bitmap.UnlockBits(bitmapData);
return bitmap;
}
They seem to be not working,
What has been the problem do you think?
N.B.
Driver program,
public class MainClass
{
public static void Main(string [] args)
{
Bitmap inputBmp = (Bitmap)Bitmap.FromFile(#"cameraman.gif");
byte[] bytes = Converter.BitmapToByteArray(inputBmp);//byte[65536]
Bitmap outputBmp = Converter.ByteArrayToBitmap(bytes, inputBmp.Width, inputBmp.Height, PixelFormat.Format8bppIndexed);
PictureDisplayForm f = new PictureDisplayForm(inputBmp, outputBmp);
f.ShowDialog();
}
}
Okay.
I have solved it.
public static byte[] BitmapToByteArray(Bitmap image)
{
byte[] returns = null;
if (image.PixelFormat == PixelFormat.Format8bppIndexed)
{
BitmapData bitmapData = image.LockBits(
new Rectangle(0, 0, image.Width, image.Height),
ImageLockMode.ReadWrite,
image.PixelFormat);
int noOfPixels = image.Width * image.Height;
int colorDepth = Bitmap.GetPixelFormatSize(image.PixelFormat);
int step = colorDepth / 8;
byte[] bytes = new byte[noOfPixels * step];
IntPtr address = bitmapData.Scan0;
Marshal.Copy(address, bytes, 0, bytes.Length);
////////////////////////////////////////////////
///
returns = (byte[])bytes.Clone();
///
////////////////////////////////////////////////
Marshal.Copy(bytes, 0, address, bytes.Length);
image.UnlockBits(bitmapData);
}
else
{
throw new Exception("8bpp indexed image required");
}
return returns;
}
public static Bitmap ByteArray1dToBitmap(byte[] bytes, int width, int height)
{
PixelFormat pixelFormat = PixelFormat.Format8bppIndexed;
Bitmap bitmap = new Bitmap(width, height, pixelFormat);
// Set the palette for gray shades
ColorPalette pal = bitmap.Palette;
for (int i = 0; i < pal.Entries.Length; i++)
{
pal.Entries[i] = Color.FromArgb(i, i, i);
}
bitmap.Palette = pal;
BitmapData bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, pixelFormat);
int colorDepth = Bitmap.GetPixelFormatSize(pixelFormat);
int noOfChannels = colorDepth / 8;
unsafe
{
byte* address = (byte*)bitmapData.Scan0;
int area = width * height;
int size = area * noOfChannels;
for (int i = 0; i < area; i++)
{
address[i] = bytes[i];//262144 bytes
}
}
//////////////////////////////////////////////////////////////
bitmap.UnlockBits(bitmapData);
return bitmap;
}
I'm trying to create an 8-bit image with a solid background color. It seems like it should be pretty straight forward but the details on the file list it as 32-bit color depth. What am I missing?
public void CreateImage()
{
var bmpOut = new Bitmap(300, 300);
var g = Graphics.FromImage(bmpOut);
g.FillRectangle(new SolidBrush(Color.Gray), 0, 0, 300, 300);
var stream = new MemoryStream();
bmpOut.Save(stream, GetPngCodecInfo(), GetEncoderParameters());
bmpOut.Save(#"C:\image.png", GetPngCodecInfo(), GetEncoderParameters());
}
public EncoderParameters GetEncoderParameters()
{
var parameters = new EncoderParameters();
parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 8);
return parameters;
}
public ImageCodecInfo GetPngCodecInfo()
{
var encoders = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo codecInfo = null;
foreach (var imageCodecInfo in encoders)
{
if (imageCodecInfo.FormatID != ImageFormat.Png.Guid)
continue;
codecInfo = imageCodecInfo;
break;
}
return codecInfo;
}
Use this constructor to specify a pixel format : http://msdn.microsoft.com/en-us/library/3z132tat.aspx
Since you cannot create a Graphics from an indexed pixel format, you can only write raw pixels to a 8-bit image.
Bitmap bitmap = new Bitmap(32, 32, PixelFormat.Format8bppIndexed);
var bitmapData = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), ImageLockMode.ReadWrite, bitmap.PixelFormat);
Random random=new Random();
byte[] buffer=new byte[bitmap.Width*bitmap.Height];
random.NextBytes(buffer);
Marshal.Copy(buffer,0,bitmapData.Scan0,buffer.Length);
bitmap.UnlockBits(bitmapData);
bitmap.Save("test.bmp",ImageFormat.Bmp);
You can either use such code on WinForms : http://www.codeproject.com/Articles/17162/Fast-Color-Depth-Change-for-Bitmaps
Or if you can reference this class from WPF it will be much easier :
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.formatconvertedbitmap(v=vs.85).aspx
You could also create the image at a higher bit rate and then convert it to 8 bits just before saving. This would allow you to use a Graphics context when creating the image. See this question for suggestions on how to convert to 8 bits:C# - How to convert an Image into an 8-bit color Image?
ImageExtensions.cs
using System.Runtime.InteropServices;
using System.Linq;
using System.Drawing.Imaging;
using System.Drawing;
using System;
public static partial class ImageExtensions {
public static ColorPalette ToGrayScale(this ColorPalette palette) {
var entries=palette.Entries;
for(var i=entries.Length; i-->0; entries[i]=entries[i].ToGrayScale())
;
return palette;
}
public static Color ToGrayScale(this Color color, double[] luminance=null) {
var list=(luminance??new[] { 0.2989, 0.5870, 0.1140 }).ToList();
var channel=new[] { color.R, color.G, color.B };
var c=(byte)Math.Round(list.Sum(x => x*channel[list.IndexOf(x)]));
return Color.FromArgb(c, c, c);
}
public static Bitmap To8bppIndexed(this Bitmap original) {
var rect=new Rectangle(Point.Empty, original.Size);
var pixelFormat=PixelFormat.Format8bppIndexed;
var destination=new Bitmap(rect.Width, rect.Height, pixelFormat);
using(var source=original.Clone(rect, PixelFormat.Format32bppArgb)) {
var destinationData=destination.LockBits(rect, ImageLockMode.WriteOnly, pixelFormat);
var sourceData=source.LockBits(rect, ImageLockMode.ReadOnly, source.PixelFormat);
var destinationSize=destinationData.Stride*destinationData.Height;
var destinationBuffer=new byte[destinationSize];
var sourceSize=sourceData.Stride*sourceData.Height;
var sourceBuffer=new byte[sourceSize];
Marshal.Copy(sourceData.Scan0, sourceBuffer, 0, sourceSize);
source.UnlockBits(sourceData);
destination.Palette=destination.Palette.ToGrayScale();
var list=destination.Palette.Entries.ToList();
for(var y=destination.Height; y-->0; ) {
for(var x=destination.Width; x-->0; ) {
var pixelIndex=y*destination.Width+x;
var sourceIndex=4*pixelIndex;
var color=
Color.FromArgb(
sourceBuffer[0+sourceIndex],
sourceBuffer[1+sourceIndex],
sourceBuffer[2+sourceIndex],
sourceBuffer[3+sourceIndex]
).ToGrayScale();
destinationBuffer[pixelIndex]=(byte)list.IndexOf(color);
}
}
Marshal.Copy(destinationBuffer, 0, destinationData.Scan0, destinationSize);
destination.UnlockBits(destinationData);
}
return destination;
}
}
Call bmpOut=bmpOut.To8bppIndexed(); before you it save to file.
I made this code to receive an image and convert it to bitmap image but it doesn't work.
Here is the code:
public void ReceiveImage()
{
NetworkStream stream = new NetworkStream(socket);
byte[] data = new byte[4];
stream.read(data,0,data.length,0)
int size = BitConverter.ToInt32(data,0);
data = new byte[size];
stream.read(data,0,data.length)
MemoryStream imagestream = new MemoryStream(data);
Bitmap bmp = new Bitmap(imagestream);
picturebox1.Image = bmp;
}
It gets to:
Bitmap bmp = new Bitmap(imagestream);
And gives me this error:
Parameter is not valid
This is an alternative method
int w= 100;
int h = 200;
int ch = 3; //number of channels (ie. assuming 24 bit RGB in this case)
byte[] imageData = new byte[w*h*ch]; //you image data here
Bitmap bitmap = new Bitmap(w,h,PixelFormat.Format24bppRgb);
BitmapData bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
IntPtr pNative = bmData.Scan0;
Marshal.Copy(imageData,0,pNative,w*h*ch);
bitmap.UnlockBits(bmData);
You are probably not receiving enough bytes in stream.read(data,0,data.length) since Read does not ensure that it will read data.length bytes. you have to check its return value and continue to read till data.Length bytes are read.
See : Stream.Read Method's return value
int read = 0;
while (read != data.Length)
{
read += stream.Read(data, read, data.Length - read);
}
PS: I am assuming lengths and reads are typos.
I assume you have a table and want to receive the picture from database.
int cout = ds.Tables["TableName"].Rows.Count;
if (cout > 0)
{
if (ds.Tables["TableName"].Rows[cout - 1]["Image"] != DBNull.Value)
{
var data = (byte[])(ds.Tables["TableName"].Rows[cout - 1]["Image"]);
var stream = new MemoryStream(data);
pictureBox1.Image = Image.FromStream(stream);
}
else
{
pictureBox1.Image = null;
}
}
Try this:
int size = BitConverter.ToInt32(data.Reverse().ToArray(),0);
I'm loading up an image into a BitmapImage and convert this into an array of PixelColor's. What I would like is to be able to manipulate some of these pixels to make them Lighter/Darker/Transparent but I can't seem to get it to work. It does work to set it to a certain color but the alpha channel is ignored.
It's a WPF app using C#4
Thanks!
And the code...
namespace BitmapTest {
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Image = System.Windows.Controls.Image;
public partial class MainWindow {
public MainWindow() {
InitializeComponent();
LoadImage();
}
[DllImport("gdi32")]
private static extern int DeleteObject(IntPtr o);
public static BitmapSource LoadBitmap(Bitmap source) {
var ip = source.GetHbitmap();
try {
return Imaging.CreateBitmapSourceFromHBitmap(ip,
IntPtr.Zero, Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
} finally {
DeleteObject(ip);
}
}
private void LoadImage() {
var i = new Image();
var src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri("road.jpg", UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
var pixels = GetPixels(src);
for (var x = 0; x < Math.Min(50, pixels.GetLength(0)); x++) {
for (var y = 0; y < Math.Min(50, pixels.GetLength(1)); y++) {
pixels[x, y] = new PixelColor {Alpha = 100, Red = pixels[x, y].Red, Green = pixels[x, y].Green, Blue = pixels[x, y].Blue};
}
}
var bitmap = new WriteableBitmap(src.PixelWidth, src.PixelHeight, src.DpiX, src.DpiY, src.Format, src.Palette);
PutPixels(bitmap, pixels, 0, 0);
i.Source = bitmap;
i.Stretch = Stretch.Fill;
RootGrid.Children.Add(i);
}
public PixelColor[,] GetPixels(BitmapSource source) {
if (source.Format != PixelFormats.Bgra32)
source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);
var pixels = source.CopyPixels();
return pixels;
}
public void PutPixels(WriteableBitmap bitmap, PixelColor[,] pixels, int x, int y) {
var width = pixels.GetLength(0);
var height = pixels.GetLength(1);
var sourceRect = new Int32Rect(0, 0, width, height);
bitmap.WritePixels(sourceRect, pixels, width*4, x, y);
}
[StructLayout(LayoutKind.Sequential)]
public struct PixelColor {
public byte Blue;
public byte Green;
public byte Red;
public byte Alpha;
}
}
public static class BitmapSourceHelper {
public static MainWindow.PixelColor[,] CopyPixels(this BitmapSource source) {
if (source.Format != PixelFormats.Bgra32)
source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);
var pixels = new MainWindow.PixelColor[source.PixelWidth, source.PixelHeight];
var stride = source.PixelWidth * ((source.Format.BitsPerPixel + 7) / 8);
var pinnedPixels = GCHandle.Alloc(pixels, GCHandleType.Pinned);
source.CopyPixels(
new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight),
pinnedPixels.AddrOfPinnedObject(),
pixels.GetLength(0) * pixels.GetLength(1) * 4,
stride);
pinnedPixels.Free();
return pixels;
}
}
}
Here is an example of lightening and darkening an image in a windows forms app. The code here is based the Brightness filter section of an article on The Code Project site: Image Processing for Dummies with C# and GDI+ Part 1.
public Bitmap Lighten(Bitmap bitmap, int amount)
{
if (amount < -255 || amount > 255)
return bitmap;
// GDI+ still lies to us - the return format is BGR, NOT RGB.
BitmapData bmData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int stride = bmData.Stride;
System.IntPtr Scan0 = bmData.Scan0;
int nVal = 0;
unsafe
{
byte* p = (byte*)(void*)Scan0;
int nOffset = stride - bitmap.Width * 3;
int nWidth = bitmap.Width * 3;
for (int y = 0; y < bitmap.Height; ++y)
{
for (int x = 0; x < nWidth; ++x)
{
nVal = (int)(p[0] + amount);
if (nVal < 0) nVal = 0;
if (nVal > 255) nVal = 255;
p[0] = (byte)nVal;
++p;
}
p += nOffset;
}
}
bitmap.UnlockBits(bmData);
return bitmap;
}
private void btnLighten_Click(object sender, EventArgs e)
{
Bitmap image = pictureBox1.Image as Bitmap;
pictureBox1.Image = Lighten(image, 10);
}
private void btnDarken_Click(object sender, EventArgs e)
{
Bitmap image = pictureBox1.Image as Bitmap;
pictureBox1.Image = Lighten(image, -10);
}
This code would adjusts a given rectangle in the image, according to brightness, contrast, alpha, gamma:
Bitmap clonedImage = originalImage.Clone(rect, originalImage.PixelFormat);
float gamma = 1.0f; // no change in gamma
float adjustedBrightness = brightness - 1.0f;
// create matrix that will brighten and contrast the image
float[][] ptsArray ={
new float[] {contrast, 0, 0, 0, 0}, // scale red
new float[] {0, contrast, 0, 0, 0}, // scale green
new float[] {0, 0, contrast, 0, 0}, // scale blue
new float[] {0, 0, 0, alpha, 0},
new float[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1}};
var imageAttributes = new ImageAttributes();
imageAttributes.ClearColorMatrix();
imageAttributes.SetColorMatrix(new ColorMatrix(ptsArray), ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
imageAttributes.SetGamma(gamma, ColorAdjustType.Bitmap);
// Copy back to the original image from the cloned image
Graphics g = Graphics.FromImage(originalImage);
g.DrawImage(clonedImage, new Rectangle(0, 0, clonedImage.Width, clonedImage.Height)
, rect.left, rect.top, rect.Width, rect.Height,
GraphicsUnit.Pixel, imageAttributes);
g.Flush();
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