I'm plotting some scatter graphs from SQL data in a c# program. I would like automatically save these graphs as they populate. I have the following code which saves the Jpeg files, but when I open them, they are empty. I'm plotting multiple graphs at once.
Any help is appreciated.
public partial class XYplotForm : Form
{
public XYplotForm()
{
InitializeComponent();
}
public void Plot(Double[] freq, Double[] amp, Double[] bw, string name)
{
scatterGraph1.PlotXY(freq, amp);
tbName.Text = name;
Bitmap image = new Bitmap(scatterGraph1.Width, scatterGraph1.Height);
Rectangle target_bounds = default(Rectangle);
target_bounds.Width = scatterGraph1.Width;
target_bounds.Height = scatterGraph1.Height;
target_bounds.X = 0;
target_bounds.Y = 0;
scatterGraph1.DrawToBitmap(image, target_bounds);
string filename = "C:\\Graph\\" + name + ".Jpeg";
image.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
xyForm = new XYplotForm();
xyForm.Plot(freqLC40, ampMaxLC40, "LC-40 Max Amplitude");
xyForm.Show();
Bitmap image = new Bitmap(xyForm.Width, xyForm.Height);
System.Drawing.Rectangle target_bounds = default(System.Drawing.Rectangle);
target_bounds.Width = xyForm.Width;
target_bounds.Height = xyForm.Height;
target_bounds.X = 0;
target_bounds.Y = 0;
xyForm.DrawToBitmap(image, target_bounds);
string filename = "C:\\Graph\\LC40_Max Amplitude.Png";
image.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
Related
I'm trying to add images from a folder and their names below each image. In master slide[0] there should be Title. My problem is that my code is generating single PowerPoint file for each image instead of adding all images to one PowerPoint file. Can someone help me with my come or simar code that can work out
I've attached an image of what I'm trying to achieve.
Here's the code I'm working with using C# and GemBoxPresentation API:
//Create new powerpoint presentation
var presentation = new PresentationDocument();
//change the path format
string dir = txtPath.Text.Replace("/", "\\");
fontRootFolder = dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, "");
string workingPath = Application.StartupPath + #"\Zip Extracts\" + fontRootFolder + "\\png";
if (Directory.Exists(workingPath))
{
// Get the directory
DirectoryInfo ImagePath = new DirectoryInfo(workingPath);
// Using GetFiles() method to get list of all png files present in the png folder
FileInfo[] Files = ImagePath.GetFiles();
foreach (FileInfo fi in Files)
{
for (int i = 0; i < fi.Length; i++)
{
Cursor = Cursors.WaitCursor;
// Get slide size.
var size = presentation.SlideSize;
// Set slide size.
size.SizedFor = SlideSizeType.OnscreenShow16X10;
size.Orientation = GemBox.Presentation.Orientation.Landscape;
size.NumberSlidesFrom = 1;
// Create new presentation slide.
var slide = presentation.Slides.AddNew(SlideLayoutType.Custom);
// Create first picture from path.
Picture picture = null;
using (var stream = File.OpenRead(fi.FullName))
picture = slide.Content.AddPicture(PictureContentType.Png, stream, 1.45, 1.35, 1.45, 1.35, LengthUnit.Centimeter);
var textBox = slide.Content.AddTextBox(ShapeGeometryType.Rectangle, 1.03, 1.03, 6, 6, LengthUnit.Centimeter);
var paragraph = textBox.AddParagraph();
paragraph.Format.Alignment = GemBox.Presentation.HorizontalAlignment.Center;
paragraph.AddRun(fi.Name);
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
sfd.Title = "Save PowerPoint Icons";
sfd.CheckFileExists = false;
sfd.CheckPathExists = true;
sfd.DefaultExt = "pptx";
sfd.Filter = "Powerpoint Files (*.pptx) | *.pptx";
sfd.FilterIndex = 1;
sfd.RestoreDirectory = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
//string file = sfd.FileName;
presentation.Save(sfd.FileName);
Cursor = Cursors.Default;
}
Cursor = Cursors.Default;
}
}
}
Expected PowerPoint output
I developed a similar tool.
The base class:
using System;
using System.Collections.Generic;
namespace akGraphics2Pptx
{
class GraphicsConverter
{
static string[] usageText =
{
"akGraphics2Pptx - Graphics to Powerpoint/PDF Converter",
"------------------------------------------------------",
"",
"Usage:",
"",
"akGraphics2Pptx graphics_file [graphics_file ...] output_file",
"",
"Enter more than one graphics file name to get more than one slide.",
"Type of output file can be .pptx or .pdf",
""
};
protected IEnumerable<string> getFileNames(string[] args, string[] extensions)
{
List<string> names = new List<string>();
foreach (string arg in args)
{
foreach (string ext in extensions)
{
if (arg.ToLower().EndsWith("." + ext))
{
names.Add(arg);
break;
}
}
}
return names;
}
/// <summary>
/// Create a Powerpoint file with one slide per graphics file argument.
/// The arguments can have any order. The files are distinguished by their extensions.
/// </summary>
/// <param name="args">The arguments</param>
public virtual void convert(string[] args)
{
}
protected void usage()
{
foreach (string s in usageText)
{
Console.WriteLine(s);
}
}
}
}
The specific converter for PowerPoint output (I also have a PDF output):
using System;
using System.Collections.Generic;
using System.Linq;
using Ppt = Microsoft.Office.Interop.PowerPoint;
using static Microsoft.Office.Core.MsoTriState;
using System.IO;
namespace akGraphics2Pptx
{
class Graphics2PptxConverter : GraphicsConverter
{
private static string[] knownGraphicsFileExtensions = { "gif", "jpg", "png", "tif", "bmp", "wmf", "emf" };
private static string[] powerpointFileExtensions = { "ppt", "pptx" };
private IEnumerable<string> getGraphicsFileNames(string[] args)
{
return getFileNames(args, knownGraphicsFileExtensions);
}
private IEnumerable<string> getPowerpointFileNames(string[] args)
{
return getFileNames(args, powerpointFileExtensions);
}
/// <summary>
/// Create a Powerpoint file with one slide per graphics file argument.
/// The arguments can have any order. The files are distinguished by their extensions.
/// </summary>
/// <param name="args">The arguments</param>
public void convert(string[] args)
{
var graphicsFileNames = getGraphicsFileNames(args);
var powerpointFileNames = getPowerpointFileNames(args);
if (!graphicsFileNames.Any() || (powerpointFileNames.Count() != 1))
{
usage();
}
else
{
// inspired by http://stackoverflow.com/a/26372266/1911064
Ppt.Application pptApplication = new Ppt.Application();
// Create the Presentation File
Ppt.Presentation pptPresentation =
pptApplication.Presentations.Add(WithWindow: msoFalse);
Ppt.CustomLayout customLayout =
pptPresentation.SlideMaster.CustomLayouts[Ppt.PpSlideLayout.ppLayoutText];
foreach (string graphicsFileName in graphicsFileNames)
{
if (!File.Exists(graphicsFileName))
{
Console.WriteLine($"Graphics file {graphicsFileName} not found!");
}
else
{
// Create new Slide
Ppt.Slides slides = pptPresentation.Slides;
Ppt._Slide slide =
slides.AddSlide(Index: slides.Count + 1, pCustomLayout: customLayout);
// Add title
Ppt.TextRange objText = slide.Shapes[1].TextFrame.TextRange;
objText.Text = Path.GetFileName(graphicsFileName);
objText.Font.Name = "Arial";
objText.Font.Size = 32;
Ppt.Shape shape = slide.Shapes[2];
objText = shape.TextFrame.TextRange;
objText.Text = "Content goes here\nYou can add text";
string fullName = Path.GetFullPath(graphicsFileName);
slide.Shapes.AddPicture(fullName, msoFalse, msoTrue, shape.Left, shape.Top, shape.Width, shape.Height);
slide.NotesPage.Shapes[2].TextFrame.TextRange.Text = graphicsFileName;
}
}
string pptFullName = Path.GetFullPath(powerpointFileNames.First());
Console.WriteLine("Powerpoint file created: " + pptFullName);
Console.WriteLine("Graphics slides: " + pptPresentation.Slides.Count);
Console.WriteLine("");
pptPresentation.SaveAs(pptFullName, Ppt.PpSaveAsFileType.ppSaveAsDefault, msoTrue);
pptPresentation.Close();
pptApplication.Quit();
}
}
}
}
Aspose.Slides for .NET is a Presentation Processing API for PowerPoint and OpenOffice formats. Aspose.Slides enable applications to read, write, protect, modify and convert presentations in .NET C#. Manage presentation text, shapes, charts, tables & animations, add audio & video to slides and preview slides.
More Link: https://products.aspose.com/slides/net/
internal class Program
{
static void Main(string[] args)
{
string[] filesindirectory = Directory.GetFiles(#"C:\\IMG");// file folder
string NameOfPPT = "_PPT_" + DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss");
//////////// var workbook = new Workbook(img);
//////////// workbook.Save(img);
using (Presentation pres = new Presentation())
{
int SlideIndex = 0;
foreach (string img in filesindirectory)
{
int alpha = 200, red = 200, green = 200, blue = 200;
pres.Slides.AddEmptySlide(pres.LayoutSlides[SlideIndex]);
// Get the first slide
ISlide slide = pres.Slides[SlideIndex];
//Add an AutoShape of Rectangle type
IAutoShape ashp = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 5, 5, 700, 30);
//Add ITextFrame to the Rectangle
string Header = "Store: Name of Store |"+ SlideIndex.ToString() + " Visite Date: 2022-Sep-20 |" + "Category: ABC" + SlideIndex.ToString();
ashp.AddTextFrame(Header);
//Change the text color to Black (which is White by default)
ashp.TextFrame.Paragraphs[0].Portions[0].PortionFormat.FillFormat.FillType = FillType.Solid;
ashp.TextFrame.Paragraphs[0].Portions[0].PortionFormat.FillFormat.SolidFillColor.Color = Color.Black;
//Change the line color of the rectangle to White
ashp.ShapeStyle.LineColor.Color = System.Drawing.Color.DarkGoldenrod;
pres.HeaderFooterManager.SetAllHeadersText("Adding Header");
pres.HeaderFooterManager.SetAllHeadersVisibility(true);
pres.HeaderFooterManager.SetAllFootersText("System Auto generated");
pres.HeaderFooterManager.SetAllFootersVisibility(true);
// pres.HeaderFooterManager.SetAllDateTimesText(DateTime.Now.ToString("dd/MM/yyyy"));
// pres.HeaderFooterManager.SetAllDateTimesVisibility(true);
SlideIndex++;
// Instantiate the ImageEx class
System.Drawing.Image imgs = (System.Drawing.Image)new Bitmap(img);
IPPImage imgx = pres.Images.AddImage(imgs);
// Add Picture Frame with height and width equivalent of Picture
//IPictureFrame pf = slide.Shapes.AddPictureFrame(ShapeType.Rectangle, 5, 5, 707, 525, imgx);// full placed image
IPictureFrame pf = slide.Shapes.AddPictureFrame(ShapeType.Rectangle, 60,100, 600, 400, imgx);
// Apply some formatting to PictureFrameEx
pf.LineFormat.FillFormat.FillType = FillType.Gradient;
pf.LineFormat.FillFormat.SolidFillColor.Color = Color.Black;
pf.LineFormat.Width = 5;
pf.Rotation = 0;
// Get the center of the slide and calculate watermark's position
PointF center = new PointF(pres.SlideSize.Size.Width / 2, pres.SlideSize.Size.Height / 2);
float width = 100;
float height = 50;
float x = center.X - width / 2;
float y = center.Y - height / 2;
// Add watermark shape
IAutoShape watermarkShape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, x, y, width, height);
// Set fill type
watermarkShape.FillFormat.FillType = FillType.NoFill;
watermarkShape.LineFormat.FillFormat.FillType = FillType.NoFill;
// Set rotation angle
watermarkShape.Rotation = -45;
// Set text
ITextFrame watermarkTextFrame = watermarkShape.AddTextFrame("OOOOOOPPPPP");
IPortion watermarkPortion = watermarkTextFrame.Paragraphs[0].Portions[0];
// Set font size and fill type of the watermark
watermarkPortion.PortionFormat.FontHeight = 20;
watermarkPortion.PortionFormat.FillFormat.FillType = FillType.Solid;
watermarkPortion.PortionFormat.FillFormat.SolidFillColor.Color = System.Drawing.Color.FromArgb(alpha, red, green, blue);
// Lock Shapes from modifying
watermarkShape.ShapeLock.SelectLocked = false;
watermarkShape.ShapeLock.SizeLocked = false;
watermarkShape.ShapeLock.TextLocked = false;
watermarkShape.ShapeLock.PositionLocked = false;
watermarkShape.ShapeLock.GroupingLocked = false;
}
pres.Save(#"C:\\IMG\\PPT\\" + NameOfPPT + ".pptx", Aspose.Slides.Export.SaveFormat.Pptx);
}
}
}
Using free plugin
public bool createPPT()
{
var data = DbWORKINGDbContext.AMR_IMG_TO_PPT_POC.Where(c => c.PPTSlideInserted == false && c.Downloaded == true).ToList();
// var data = DbWORKINGDbContext.AMR_IMG_TO_PPT_POC.Take(10).ToList();
if (data.Count > 0)
{
Application pptApplication = new Application();
Microsoft.Office.Interop.PowerPoint.Slides slides;
Microsoft.Office.Interop.PowerPoint._Slide slide;
Microsoft.Office.Interop.PowerPoint.TextRange objText;
// Microsoft.Office.Interop.PowerPoint.TextRange objText2;
// Create the Presentation File
Presentation pptPresentation = pptApplication.Presentations.Add(MsoTriState.msoTrue);
Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = pptPresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
int SlideIndex = 1;
foreach (AMR_IMG_TO_PPT_POC POCdata in data)
{
var pictureFileName = ImageToPptApp.Util.Constant.ImageStorePath + POCdata.Id + ".jpg";
var StoreName = POCdata.StoreName;
var Url = POCdata.FileCloudUrl;
var Filename = POCdata.Id;
var Titile = POCdata.Title;
var PictureTime = POCdata.PictureTimeStamp;
string Header = "Store: " + StoreName.ToString() + " | Date Time:" + PictureTime.ToString() + " | Titile: " + Titile.ToString();
// Create new Slide
slides = pptPresentation.Slides;
slide = slides.AddSlide(SlideIndex, customLayout);
// Add title
objText = slide.Shapes[1].TextFrame.TextRange;
objText.Text = Header;
objText.Font.Name = "Arial";
objText.Font.Size = 20;
//objText2 = slide.Shapes[2].TextFrame.TextRange;
//objText2.Text = "test";
//objText2.Font.Name = "Arial";
//objText2.Font.Size = 10;
//objText = slide.Shapes[2].TextFrame.TextRange;
//objText.Text = "pp";
Microsoft.Office.Interop.PowerPoint.Shape shape = slide.Shapes[2];
slide.Shapes.AddPicture(pictureFileName, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 100, 100, 600, 400);
slide.NotesPage.Shapes[2].TextFrame.TextRange.Text = "MintPlus";
SlideIndex++;
}
pptPresentation.SaveAs(ImageToPptApp.Util.Constant.PptStorePath + "ppp"+ ".pptx", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue);
pptPresentation.Close();
pptApplication.Quit();
}
return true;
}
I'm attempting to create a model viewer for a game to try and learn SharpDX but the game uses .DDS files and the viewer can only read .BMPs. I've looked far and wide on the webs and the only things I can find are load them but don't seem to work for SharpDX (I don't know im a noob :D)
using SharpDX.Direct3D11;
using SharpDX.WIC;
namespace ModelViewer.Programming.GraphicClasses
{
public class TextureClass
{
public ShaderResourceView TextureResource { get; private set; }
public bool Init(Device device, string fileName)
{
try
{
using (var texture = LoadFromFile(device, new ImagingFactory(), fileName))
{
ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription()
{
Format = texture.Description.Format,
Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
};
srvDesc.Texture2D.MostDetailedMip = 0;
srvDesc.Texture2D.MipLevels = -1;
TextureResource = new ShaderResourceView(device, texture, srvDesc);
device.ImmediateContext.GenerateMips(TextureResource);
}
return true;
}
catch
{
return false;
}
}
public void Shutdown()
{
TextureResource?.Dispose();
TextureResource = null;
}
public Texture2D LoadFromFile(Device device, ImagingFactory factory, string fileName)
{
using (var bs = LoadBitmap(factory, fileName))
return CreateTextureFromBitmap(device, bs);
}
public BitmapSource LoadBitmap(ImagingFactory factory, string filename)
{
var bitmapDecoder = new BitmapDecoder(factory, filename, DecodeOptions.CacheOnDemand);
var result = new FormatConverter(factory);
result.Initialize(bitmapDecoder.GetFrame(0), SharpDX.WIC.PixelFormat.Format32bppPRGBA, BitmapDitherType.None, null, 0.0, BitmapPaletteType.Custom);
return result;
}
public Texture2D CreateTextureFromBitmap(Device device, BitmapSource bitmapSource)
{
int stride = bitmapSource.Size.Width * 4;
using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true))
{
bitmapSource.CopyPixels(stride, buffer);
return new Texture2D(device, new Texture2DDescription()
{
Width = bitmapSource.Size.Width,
Height = bitmapSource.Size.Height,
ArraySize = 1,
BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget,
Usage = ResourceUsage.Default,
CpuAccessFlags = CpuAccessFlags.None,
Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
MipLevels = 1,
OptionFlags = ResourceOptionFlags.GenerateMipMaps,
SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
},
new SharpDX.DataRectangle(buffer.DataPointer, stride));
}
}
}
}
I have a feeling this will need to be completely redone to utilize the DDS format. Is it easier to simply read one and then convert it to a bitmap?
I think i need to store the string s and bitmap bmp in an array then i think i have to pick one image in the bmp array to show in the picture box but im not sure how.
public partial class capstoneProjectForm : Form
{
string imageName;
//string[] a;
Bitmap[] bit;
string[] folder;
int numOfPics;
int num = 0;
public capstoneProjectForm()
{
InitializeComponent();
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
// a = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
string resFolder = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources");
foreach (string s in Directory.EnumerateFiles(resFolder, "*.jpg"))
{
using (Bitmap bmp = new Bitmap(s))
{
}
if (s.Equals(imageName))
{
pictureBox.Image = ;
}
}
I am creating a digital clock user control. Here is the code:
public partial class DigitalClockControl : UserControl
{
public DigitalClockControl()
{
InitializeComponent();
}
private static List<Image> Sprite;
private static Clock data;
public Clock Data
{
get { return DigitalClockControl.data; }
set { DigitalClockControl.data = value;
int min = data.Min;
int sec = data.Sec;
Min1.Image = Sprite[min / 10];
Min2.Image = Sprite[min % 10];
Sec1.Image = Sprite[sec / 10];
Sec2.Image = Sprite[sec % 10];
}
}
private void DigitalClockControl_Load(object sender, EventArgs e)
{
Sprite = new List<Image>();
LoadSprite();
data = new Clock();
}
private void LoadSprite()
{
string path = Directory.GetParent((Directory.GetParent((Directory.GetCurrentDirectory().ToString())).ToString())).ToString();
Image img;
for (int i = 0; i <= 9; ++i)
{
img = Image.FromFile(path + "\\" + i.ToString() + ".png");
Sprite.Add(img);
}
}
}
When I tried to drag this user control to the form, it raised an error like this:
Failed to create component 'DigitalClockControl'. The error messages follows:'System.IO.FileNotFoundException: D:\\0.png...
I don't know why it loads an image from D:\. All the images are at the path above. If I copy the image to D:\, the program works fine. I tried to go to the InitializeComponent() function but cannot file any code makes the program load the image.
Edit: solved by adding user control by code in Form.cs. Thank you very much for all your help.
You should place all images into debug\\bin\\images folder. so, when you install the application you can find all the images in Application Folder (Application.StartupPat + "\\Images").
CODE:
string path = Application.StartupPath + "\\Images";
Image img;
for (int i = 0; i <= 9; ++i)
{
img = Image.FromFile(path + "\\" + i.ToString() + ".png");
Sprite.Add(img);
}
Alternatively, you could use Assembly.GetExecutingAssembly() (that is the assembly containing your control) and use its Location Property to figure out where the root of your component is. You could put the images for your clock into a folder next to your assembly. By doing so, deployment would be easy and clear.
I've got an image upload page that works just fine when I only upload the files.
I added a 'Create Thumbnail' function. It looks like the file system has a handle on the images when the thumbnail process starts.
I get the 'unspecified GDI+ error' only when the image is over about 250K. When the files are below 250K, thumbnails are created as expected.
What are my options? Is there an elegant solution here? I want something not hacky.
Also, I am using HttpFileCollection so we can upload multiple images at one time. I've tried to use .Dispose on the Thumbnail creation, but it fails before we get to this point.
public void Upload_Click(object Sender, EventArgs e)
{
string directory = Server.MapPath(#"~\images\");
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileName = hpf.FileName;
fileName = fileName.Replace(" ", "");
hpf.SaveAs(fileName);
createThumbnail(fileName);
}
}
}
private void createThumbnail(string filename)
{
Image image = Image.FromFile(filename);
Image thumb = image.GetThumbnailImage(100,100, () => false, IntPtr.Zero);
thumb.Save(filename);
image.Dispose();
thumb.Dispose();
}
Please let me know if this works any better:
public string ImageDirectory { get { return Server.MapPath(#"~\images\"); } }
public void OnUploadClick(object sender, EventArgs e)
{
var files = HttpContext.Request.Files.AllKeys.AsEnumerable()
.Select(k =>HttpContext.Request.Files[k]);
foreach(var file in files)
{
if(file.ContentLength <= 0)
continue;
string savePath = GetFullSavePath(file);
var dimensions = new Size(100, 100);
CreateThumbnail(file,savePath,dimensions);
}
}
private void CreateThumbnail(HttpPostedFile file,string savePath, Size dimensions)
{
using (var image = Image.FromStream(file.InputStream))
{
using (var thumb = image.GetThumbnailImage(dimensions.Width, dimensions.Height, () => false, IntPtr.Zero))
{
thumb.Save(savePath);
}
}
}
private string GetFullSavePath(HttpPostedFile file)
{
string fileName = System.IO.Path.GetFileName(file.FileName).Replace(" ", "");
string savePath = System.IO.Path.Combine(this.ImageDirectory, fileName);
return savePath;
}
Edit -
The foreach should have followed more to this pattern:
var files = HttpContext.Request.Files.AllKeys.AsEnumerable()
.Select(k =>HttpContext.Request.Files[k]);
foreach(var file in files)
{
}
You can try this code to create your thumbnails.
MemoryStream ms = new MemoryStream(File.ReadAllBytes(path));
Bitmap originalBMP = new Bitmap(ms);
int maxWidth = 200;
int maxHeight = 200;
// Calculate the new image dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
double sngRatio = Convert.ToDouble(origWidth) / Convert.ToDouble(origHeight);
// New dimensions
int newWidth = 0;
int newHeight = 0;
try
{
// max 200 by 200
if ((origWidth <= maxWidth && origHeight <= maxHeight) || origWidth <= maxWidth)
{
newWidth = origWidth;
newHeight = origHeight;
}
else
{
// Width longer (shrink width)
newWidth = 200;
newHeight = Convert.ToInt32(Convert.ToDouble(newWidth) / sngRatio);
}
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.High;
// Draw the new graphic based on the resized bitmap
oGraphics.CompositingQuality = CompositingQuality.HighSpeed;
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
// Save the new graphic file to the server
EncoderParameters p = new EncoderParameters(1);
p.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 70); // Percent Compression
MemoryStream savedBmp = new MemoryStream();
newBMP.Save(savedBmp, ImageCodecInfo.GetImageEncoders()[1], p);
// Once finished with the bitmap objects, we deallocate them.
originalBMP.Dispose();
newBMP.Dispose();
oGraphics.Dispose();
savedBmp.Dispose();
Certainly a bit more work but it does give you greater control.