Limit image size - c#

I have an OpenFileDialog in my WinForm and I want when to select an image to limit the image's size in 100 Ko and the Dimensions in 350x350.
How can I do that ??

private bool ValidFile(string filename, long limitInBytes, int limitWidth, int limitHeight)
{
var fileSizeInBytes = new FileInfo(filename).Length;
if(fileSizeInBytes > limitInBytes) return false;
using(var img = new Bitmap(filename))
{
if(img.Width > limitWidth || img.Height > limitHeight) return false;
}
return true;
}
private void selectImgButton_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if(ValidFile(openFileDialog1.FileName, 102400, 350, 350))
{
// Image is valid and U can
// Do something with image
// For example set it to a picture box
pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
}
else
{
MessageBox.Show("Image is invalid");
}
}
}

It depends on what types of images you need to support. For most common types (bmp, jpg, png), you can easily retrieve image info:
string filename = // get it from OpenFileDialog
if (new FileInfo(filename).Length > SOME_LIMIT)
{
MessageBox.Show("!!!");
}
else
{
Image img = Image.FromFile(filename);
MessageBox.Show(string.Format("{0} x {1}", img.Width, img.Height));
}
If you need more extensive support for many image formats, then I suggest using a library like ImageMagick.NET

put this as global variable
int imgSize = 0
private void button1_Click(object sender, EventArgs e)
{
Image imageFile;
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Image";
dlg.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
imageFile = Image.FromFile(dlg.FileName);
imgHeight = imageFile.Height;
if (imgHeight > 350)
{
MessageBox.Show("Not 350x350 Image", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
imgPhoto.Image = null;
}
else
{
PictureBox1.Image = new Bitmap(dlg.OpenFile());
}
}
dlg.Dispose();
}
Hope this will help.

Try this :
OpenFileDialog fileDialog = new OpenFileDialog
{
// managed GDI+ supports bmp, jpeg, gif, png and tiff.
Filter =
"Image files (*.bmp;*.jpg;*.gif;*.png;*.tiff)|*.bmp;*.jpg;*.gif;*.png;*.tiff|All files (*.*)|*.*",
};
if (fileDialog.ShowDialog() == DialogResult.OK)
{
// Many exceptions could be raised in the following code
try
{
var fileSize = new FileInfo(fileDialog.FileName);
var validFilesize = fileSize.Length <= 1024 * 100; // 100 kilo bytes
var validDimensions = false;
// free the file once we get the dimensions
using (Image image = Image.FromFile(fileDialog.FileName))
{
validDimensions = (image.Width <= 350) && (image.Height <= 350);
}
if (!validDimensions || !validFilesize)
{
MessageBox.Show("Error ! Choose another image");
}
else
{
// do something with the file here
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}

Related

Convert Tif document to PDF with PdfSharp

I’m using WinForms. In my form I have a picturebox that displays tif image documents. I’m using PdfSharp as one of my references to convert the tif documents to pdf documents. The good news is I can convert one of the tif pages that is currently displayed in the picturebox.
The problem is when I have a tif document that has more than 1 page, I cannot convert them all into on single Pdf file. For example if I have a tif document image that contains 5 pages, I would want to press a button and convert all those 5 tif pages into 5 pdf pages.
For testing here is a tif document with 5 pages.
Link: http://www.filedropper.com/sampletifdocument5pages
My Code:
using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
private string srcFile, destFile;
bool success = false;
private void Open_btn_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Image";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(dlg.FileName);
lbl_SrcFile.Text = dlg.FileName;
}
dlg.Dispose();
}
private void Save_btn_Click(object sender, EventArgs e)
{
SaveImageToPDF();
}
private void SaveImageToPDF()
{
try
{
string source = lbl_SrcFile.Text;
string savedfile = #"C:\image\Temporary.tif";
pictureBox1.Image.Save(savedfile);
source = savedfile;
string destinaton = #"C:\image\new_PDF_TIF_Document.pdf";
PdfDocument doc = new PdfDocument();
var page = new PdfPage();
XImage img = XImage.FromFile(source);
if (img.Width > img.Height)
{
page.Orientation = PageOrientation.Landscape;
}
else
{
page.Orientation = PageOrientation.Portrait;
}
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]); xgr.DrawImage(img, 0, 0);
doc.Save(destinaton);
doc.Close();
img.Dispose(); //dispose img in order to free the tmp file for deletion (Make sure the PDF file is closed thats being used)
success = true;
MessageBox.Show(" File saved successfully! \n\nLocation: C:\\image\\New PDF Document.pdf", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process.Start(destinaton);
File.Delete(savedfile);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
[Edit] Added full working code...with paths hard-coded.
try
{
string destinaton = #"C:\Temp\Junk\new_PDF_TIF_Document.pdf";
Image MyImage = Image.FromFile(#"C:\Temp\Junk\Sample tif document 5 pages.tiff");
PdfDocument doc = new PdfDocument();
for (int PageIndex = 0; PageIndex < MyImage.GetFrameCount(FrameDimension.Page); PageIndex++)
{
MyImage.SelectActiveFrame(FrameDimension.Page, PageIndex);
XImage img = XImage.FromGdiPlusImage(MyImage);
var page = new PdfPage();
if (img.Width > img.Height)
{
page.Orientation = PageOrientation.Landscape;
}
else
{
page.Orientation = PageOrientation.Portrait;
}
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
xgr.DrawImage(img, 0, 0);
}
doc.Save(destinaton);
doc.Close();
MyImage.Dispose();
MessageBox.Show("File saved successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
It's been a while since I've used PdfSharp, but you should be able to call the GetFrameCount method on your image, which will tell you how many pages it has.
Then you can use the SelectActiveFrame method to choose which page is active.
PDFsharp-gdi
public static void ToPDF() {
try
{
PdfDocument doc = new PdfDocument();
string source = #"D:\TIF\bb.tif";
string destinaton = #"D:\TIF\bb.pdf";
Image img = Image.FromFile(source);
for (int PageIndex = 0; PageIndex < img.GetFrameCount(FrameDimension.Page); PageIndex++)
{
img.SelectActiveFrame(FrameDimension.Page, PageIndex);
XImage xImg = XImage.FromGdiPlusImage(img);
double width = Math.Ceiling((double)(xImg.Width * 72) / 96);
double height = Math.Ceiling((double)(xImg.Height * 72) / 96);
var page = new PdfPage();
if (xImg.Width > xImg.Height)
{
page.Orientation = PdfSharp.PageOrientation.Landscape;
}
else
{
page.Orientation = PdfSharp.PageOrientation.Portrait;
}
page.Width = width;
page.Height = height;
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
xgr.DrawImage(xImg, 0, 0, width, height);
}
doc.Save(destinaton);
doc.Close();
img.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}

Delete an image being used by another process

I am writing a winform application in C# to open an image and overlay another image on top of it.
The bottom image is a .jpg and the top one is a .bmp converted from .svg. The .jpg and the .svg are the only ones I want to keep in the folder. The .bmp works as a temp.
I was using the following code to overlay the images. But I am having trouble to delete the temp .bmp as it is used by another process. I think it is this combine code still have access to the last .bmp file.
Could anyone help me on this? Thanks.
private void buttonSearch_Click(object sender, EventArgs e)
{
FailInfo.Text = "";
deletebmp(strFolderPath);
...
// Check if the specified front image exists. Yes, show the file name and convert SVG to BMP. No, show the error msg.
if (File.Exists(strFilePathF))
{
labelFront.Text = strFileNameF;
var svgConvert = SvgDocument.Open(svgFilePathF);
svgConvert.Draw().Save(bmpFilePathF);
pictureBoxFront.Image = Image.FromFile(strFilePathF);
}
else
{
labelFront.Text = "Couldn't find the file!";
pictureBoxFront.Image = null;
}
// Check if the specified back image exists. Yes, show the file name and convert SVG to BMP. No, show the error msg.
if (File.Exists(strFilePathBF))
{
labelBack.Text = strFileNameBF;
strFilePathB = strFilePathBF;
pictureBoxBack.Image = Image.FromFile(strFilePathB);
labelResult.Text = "FAIL";
labelResult.BackColor = Color.FromArgb(255, 0, 0);
var svgConvert = SvgDocument.Open(svgFilePathBF);
bmpFilePathB = strFolderPath + strFileNameBF + ".bmp";
svgConvert.Draw().Save(bmpFilePathB);
svgFilePathB = svgFilePathBF;
inspectionres(svgFilePathB);
labelreason.Visible = true;
}
else if (File.Exists(strFilePathBP))
{
labelBack.Text = strFileNameBP;
strFilePathB = strFilePathBP;
pictureBoxBack.Image = Image.FromFile(strFilePathB);
labelResult.Text = "PASS";
labelResult.BackColor = Color.FromArgb(0, 255, 0);
var svgConvert = SvgDocument.Open(svgFilePathBP);
bmpFilePathB = strFolderPath + strFileNameBP + ".bmp";
svgConvert.Draw().Save(bmpFilePathB);
svgFilePathB = svgFilePathBP;
inspectionres(svgFilePathB);
labelreason.Visible = false;
}
else
{
labelBack.Text = "Couldn't find the file!";
pictureBoxBack.Image = null;
labelResult.Text = "ERROR";
labelResult.BackColor = Color.FromArgb(0, 255, 255);
labelreason.Visible = false;
}
}
//
// Overlay the SVG file on top of the JPEG file
//
private Bitmap Combine(string jpegFile, string bmpFile)
{
Image image1 = Image.FromFile(jpegFile);
Image image2 = Image.FromFile(bmpFile);
Bitmap temp = new Bitmap(image1.Width, image1.Height);
using (Graphics g = Graphics.FromImage(temp))
{
g.DrawImageUnscaled(image1, 0, 0);
g.DrawImageUnscaled(image2, 0, 0);
}
return temp;
}
//
// Show the overlaid graphic in the picturebox
//
private void checkBoxOverlay_CheckedChanged(object sender, EventArgs e)
{
try
{
if (FindFront)
if (checkBoxOverlay.Checked)
pictureBoxFront.Image = Combine(strFilePathF, bmpFilePathF);
else
pictureBoxFront.Image = Image.FromFile(strFilePathF);
else
pictureBoxFront.Image = null;
if (FindBack)
if (checkBoxOverlay.Checked)
pictureBoxBack.Image = Combine(strFilePathB, bmpFilePathB);
else
pictureBoxBack.Image = Image.FromFile(strFilePathB);
else
pictureBoxBack.Image = null;
}
catch (Exception ex)
{
MessageBox.Show("Error loading image" + ex.Message);
}
}
//
// Option of changing the image folder
//
private void buttonPath_Click(object sender, EventArgs e)
{
FolderBrowserDialog FolderBrowserDialog1 = new FolderBrowserDialog();
if (FolderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
strFolderPath = FolderBrowserDialog1.SelectedPath + "\\";
}
}
//
// Pull the inspection result info from the SVG file
//
private void inspectionres(string filename)
{
XDocument document = XDocument.Load(filename);
XElement svg_Element = document.Root;
string sb = null;
var faillist = (from svg_path in svg_Element.Descendants("{http://www.w3.org/2000/svg}text") select svg_path).ToList();
foreach (var item in faillist)
{
sb += item.ToString();
}
}
//
// Delete all the .bmp files generated from .svg files
//
private void deletebmp(string path)
{
// Unload the images from the picturebox if applicable
pictureBoxFront.Image = null;
pictureBoxBack.Image = null;
string[] files = Directory.GetFiles(path, "*.bmp");
for (int i = 0; i < files.Length; i ++ )
File.Delete(files[i]);
}
}
Image implements IDisposable, so simply setting the pictureBox.Image property to null will not release resources (in your case, the file). Your Combine method also leaves the images open. You have to call Dispose before attempting to delete the file:
Image image1 = Image.FromFile(path1);
File.Delete(path1); // error - file is locked
Image image2 = Image.FromFile(path2);
image2.Dispose();
File.Delete(path2); // works
An alternative approach (and I assume you're using WinForms here, in WPF it's a little different) would be to load the bitmap from the file manually (using FromStream). Then, you can close the stream immediately and delete the file:
Image image;
using (Stream stream = File.OpenRead(path))
{
image = System.Drawing.Image.FromStream(stream);
}
pictureBox.Image = image;
File.Delete("e:\\temp\\copy1.png"); //works
Vesan's answer didn't helped me so I found an different solution.
So I can safe/open an image and if I want instantly delete the image.
i used it for my dataGridView_SelectionChanged:
private void dataGridViewAnzeige_SelectionChanged(object sender, EventArgs e)
{
var imageAsByteArray = File.ReadAllBytes(path);
pictureBox1.Image = byteArrayToImage(imageAsByteArray);
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
All above answers are perfectly fine, but I've got a different approach.
Using Image abstract class, you will not get quite a lot of options for manipulating and resizing image.
Rather you do as follows:-
Bitmap img = new Bitmap(item);
img.SetResolution(100, 100);
Image imgNew = Image.FromHbitmap(img.GetHbitmap());
pictureBox1.Image = imgNew;
img.Dispose();

Why does IrfanView say my jpg file is a png file?

My utility is supposed to resize either .jpg or .png files.
It seems to work fine in one location (at work, where I don't have IrfanView installed). But at home, when I open a *.jpg and then save it (resized), I see:
However, the image still displays fine in either case (whether I select "Yes" or "No" in the dialog.
IOW, I'm able to load and save both jpgs and pngs, and they save as such, and display fine. But IrfanView claims they are messed up.
Actually, I'm not sure how the image is saved; I was assuming it just saved it in the proper format "behind the scenes" based on the extension. Anyway, as this is a rather simple utility, I will just show all the code:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace FileResizingUtil
{
public partial class FormFileResizer : Form
{
private Image _imgToResize;
String _originalFilename = String.Empty;
public FormFileResizer()
{
InitializeComponent();
}
private void buttonChooseImage_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog
{
InitialDirectory = "c:\\",
Filter = "JPG files (*.jpg)|*.jpg| PNG files (*.png)|*.png", FilterIndex = 2, RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
_originalFilename = ofd.FileName;
_imgToResize = Image.FromFile(_originalFilename);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
// If made it to here, it must be good
String preamble = labelImgSelected.Text;
labelImgSelected.Text = String.Format("{0}{1}", preamble, _originalFilename);
textBoxOrigHeight.Text = _imgToResize.Height.ToString();
textBoxOrigWidth.Text = _imgToResize.Width.ToString();
buttonApplyPercentageChange.Enabled = true;
//buttonResizeImage.Enabled = true;
}
private void buttonResizeImage_Click(object sender, EventArgs e)
{
// Really large images take awhile, so show an hourglass
Cursor.Current = Cursors.WaitCursor;
try
{
var size = new Size { Height = Convert.ToInt32(textBoxNewHeight.Text), Width = int.Parse(textBoxNewWidth.Text) };
// Two different ways of getting the int val
Image resizedImg = FileResizeUtils.GetResizedImage(_imgToResize, size);
String fileNameSansExtension = Path.GetFileNameWithoutExtension(_originalFilename);
String fileNameExtension = Path.GetExtension(_originalFilename);
String newFilename = String.Format("{0}{1}_{2}{3}", fileNameSansExtension, size.Height, size.Width, fileNameExtension);
// If used a different extension (jpg where the original was png, or vice versa) would the Save be intelligent enough to actually save in the other format?
resizedImg.Save(newFilename);
MessageBox.Show(String.Format("Done! File saved as {0}", newFilename));
Recycle();
}
finally
{
Cursor.Current = Cursors.Default;
}
}
private void Recycle()
{
buttonResizeImage.Enabled = false;
buttonApplyPercentageChange.Enabled = false;
labelImgSelected.Text = "Image selected: ";
textBoxOrigHeight.Text = String.Empty;
textBoxOrigWidth.Text = String.Empty;
// Retain the percentage vals, as it may be that all in a batch need to be the same pair of vals
}
private void buttonApplyPercentageChange_Click(object sender, EventArgs e)
{
int origHeight = _imgToResize.Height;
int origWidth = _imgToResize.Width;
// Two ways to convert the val
double heightFactor = (double)numericUpDownHeight.Value / 100.0;
double widthFactor = Convert.ToDouble(numericUpDownWidth.Value) / 100.0;
if (heightFactor < 0 || widthFactor < 0)
{
// show an error - no negative values allowed- using updown, so that should not be possible
}
var newHeight = Convert.ToInt32(origHeight * heightFactor);
var newWidth = Convert.ToInt32(origWidth * widthFactor);
textBoxNewHeight.Text = newHeight.ToString();
textBoxNewWidth.Text = newWidth.ToString();
buttonResizeImage.Enabled = true;
}
private void textBoxNewHeight_TextChanged(object sender, EventArgs e)
{
EnableResizeButtonIfValidDimensionsEntered();
}
private void EnableResizeButtonIfValidDimensionsEntered()
{
if (String.IsNullOrWhiteSpace(textBoxOrigHeight.Text)) return;
String candidateHeight = textBoxNewHeight.Text;
String candidateWidth = textBoxNewWidth.Text;
int validHeight;
int validWidth;
buttonResizeImage.Enabled = (int.TryParse(candidateHeight, out validHeight)) &&
(int.TryParse(candidateWidth, out validWidth));
}
private void numericUpDownHeight_ValueChanged(object sender, EventArgs e)
{
if (checkBoxRetainRatio.Checked)
{
numericUpDownWidth.Value = numericUpDownHeight.Value;
}
}
private void numericUpDownWidth_ValueChanged(object sender, EventArgs e)
{
if (checkBoxRetainRatio.Checked)
{
numericUpDownHeight.Value = numericUpDownWidth.Value;
}
}
}
}
..and the GUI (just prior to hitting the "Resize Image" button:
UPDATE
Based on Eugene Sh.'ls comment, I changed my Save method to the following block:
bool success = true;
. . .
if (fileNameExtension != null && fileNameExtension.ToLower().Contains("jpg"))
{
resizedImg.Save(newFilename, ImageFormat.Jpeg);
}
else if (fileNameExtension != null &&
fileNameExtension.ToLower().Contains("png"))
{
resizedImg.Save(newFilename, ImageFormat.Png);
}
else
{
success = false;
}
if (success)
{
MessageBox.Show(String.Format("Done! File saved as {0}", newFilename));
}
else
{
MessageBox.Show("Something went awry. The file was not saved");
}
UPDATE 2
So here is my new code, implementing the suggestion, and supporting several new file types:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
namespace FileResizingUtil
{
public partial class FormFileResizer : Form
{
private Image _imgToResize;
String _originalFilename = String.Empty;
public FormFileResizer()
{
InitializeComponent();
}
private void buttonChooseImage_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog
{
InitialDirectory = "c:\\",
Filter = "JPG files (*.jpg)|*.jpg| PNG files (*.png)|*.png| BMP files (*.bmp)|*.bmp| TIFF files (*.tiff)|*.png| ICO files (*.ico)|*.ico| EMF files (*.emf)|*.emf| WMF files (*.wmf)|*.wmf",
FilterIndex = 1, RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
_originalFilename = ofd.FileName;
_imgToResize = Image.FromFile(_originalFilename);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
if (String.IsNullOrWhiteSpace(_originalFilename)) return;
// If made it to here, it must be good
String preamble = labelImgSelected.Text;
labelImgSelected.Text = String.Format("{0}{1}", preamble, _originalFilename);
textBoxOrigHeight.Text = _imgToResize.Height.ToString();
textBoxOrigWidth.Text = _imgToResize.Width.ToString();
buttonApplyPercentageChange.Enabled = true;
}
private void buttonResizeImage_Click(object sender, EventArgs e)
{
bool success = true;
// Really large images take awhile, so show an hourglass
Cursor.Current = Cursors.WaitCursor;
try
{
// Two different ways of getting the int val
var size = new Size { Height = Convert.ToInt32(textBoxNewHeight.Text), Width = int.Parse(textBoxNewWidth.Text) };
Image resizedImg = FileResizeUtils.GetResizedImage(_imgToResize, size);
String fileNameSansExtension = Path.GetFileNameWithoutExtension(_originalFilename);
String fileNameExtension = Path.GetExtension(_originalFilename);
String newFilename = String.Format("{0}{1}_{2}{3}", fileNameSansExtension, size.Height, size.Width, fileNameExtension);
if (fileNameExtension != null && fileNameExtension.ToLower().Contains("jpg"))
{
resizedImg.Save(newFilename, ImageFormat.Jpeg);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("png"))
{
resizedImg.Save(newFilename, ImageFormat.Png);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("bmp"))
{
resizedImg.Save(newFilename, ImageFormat.Bmp);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("ico"))
{
resizedImg.Save(newFilename, ImageFormat.Icon);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("tiff"))
{
resizedImg.Save(newFilename, ImageFormat.Tiff);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("emf"))
{
resizedImg.Save(newFilename, ImageFormat.Emf);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("wmf"))
{
resizedImg.Save(newFilename, ImageFormat.Wmf);
}
else
{
success = false;
}
MessageBox.Show(success
? String.Format("Done! File saved as {0}", newFilename)
: "Something went awry. The file was not saved");
Recycle();
}
finally
{
Cursor.Current = Cursors.Default;
}
}
private void Recycle()
{
buttonResizeImage.Enabled = false;
buttonApplyPercentageChange.Enabled = false;
labelImgSelected.Text = "Image selected: ";
textBoxOrigHeight.Text = String.Empty;
textBoxOrigWidth.Text = String.Empty;
// Retain the percentage vals, as it may be that all in a batch need to be the same pair of vals
}
private void buttonApplyPercentageChange_Click(object sender, EventArgs e)
{
int origHeight = _imgToResize.Height;
int origWidth = _imgToResize.Width;
// Two ways to convert the val
double heightFactor = (double)numericUpDownHeight.Value / 100.0;
double widthFactor = Convert.ToDouble(numericUpDownWidth.Value) / 100.0;
if (heightFactor < 0 || widthFactor < 0)
{
// show an error - no negative values allowed- using updown, so that should not be possible
}
var newHeight = Convert.ToInt32(origHeight * heightFactor);
var newWidth = Convert.ToInt32(origWidth * widthFactor);
textBoxNewHeight.Text = newHeight.ToString();
textBoxNewWidth.Text = newWidth.ToString();
buttonResizeImage.Enabled = true;
}
private void textBoxNewHeight_TextChanged(object sender, EventArgs e)
{
EnableResizeButtonIfValidDimensionsEntered();
}
private void EnableResizeButtonIfValidDimensionsEntered()
{
if (String.IsNullOrWhiteSpace(textBoxOrigHeight.Text)) return;
String candidateHeight = textBoxNewHeight.Text;
String candidateWidth = textBoxNewWidth.Text;
int validHeight;
int validWidth;
buttonResizeImage.Enabled = (int.TryParse(candidateHeight, out validHeight)) &&
(int.TryParse(candidateWidth, out validWidth));
}
private void numericUpDownHeight_ValueChanged(object sender, EventArgs e)
{
if (checkBoxRetainRatio.Checked)
{
numericUpDownWidth.Value = numericUpDownHeight.Value;
}
}
private void numericUpDownWidth_ValueChanged(object sender, EventArgs e)
{
if (checkBoxRetainRatio.Checked)
{
numericUpDownHeight.Value = numericUpDownWidth.Value;
}
}
}
}
From the Image.Save documentation:
If no encoder exists for the file format of the image, the Portable
Network Graphics (PNG) encoder is used. When you use the Save method
to save a graphic image as a Windows Metafile Format (WMF) or Enhanced
Metafile Format (EMF) file, the resulting file is saved as a Portable
Network Graphics (PNG) file. This behavior occurs because the GDI+
component of the .NET Framework does not have an encoder that you can
use to save files as .wmf or .emf files.
If you want to save in a different format, use the overloaded Save method, taking format as a second parameter:
Save(String, ImageFormat)
Most image viewers don't use the extension of the file to determine the type of the file, but use so called "magic numbers" (http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files). They basically check the first X bytes of the file wich is often unique to a specific image format.
My guess is, that the library you're using saves the file as PNG as default (edit: see Eugenes answer), not considering what extension you put there. IrfanView notices, that the magic number and the extension don't match but still shows the image by defaulting to the magic number.
Go to a console and print out the file. If it is a PNG file, you will see PNG displayed and it stops.
If is is JPEG, you will get a lot of garbage but should see EXIF or JFIF at the top. The very start is FF D8
Because the JPEG and PNG have different signatures, the application can tell them apart from their contents and invite the appropriate decoder.
Image applications normally identify the type of image from the contents of the stream, not the extension.

Problem with converting image to byte array

For school we have to do a project in stenography, I have chosen to use a bmp and put text into it. It works fine with normal pictures but from the moment on when you have pictures with a same byte sequence for example a white area or the image where I had the problem is this picture.
When I make from the bytearray where the text is in an image and I read it back the bytearray has changed. while the only thing I did was making an image from the bytearray and from the image back a bytearray.
This is my code:
namespace steganografie
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "bmp files (*.bmp)|*.bmp|All files (*.*)|*.*";
dialog.Title = "Select a image";
dialog.InitialDirectory = Application.ExecutablePath;
if (dialog.ShowDialog() == DialogResult.OK)
{
txtText.Enabled = true;
txtFile.Text = dialog.FileName;
byte[] arImage = imageToByteArray(Image.FromFile(txtFile.Text));
txtText.MaxLength = ((arImage.Length -54) /8)-5;
lblCharLeft.Text = txtText.MaxLength+"";
lblCharLeft.Tag = txtText.MaxLength;
picOriginal.Image = Image.FromFile(dialog.FileName);
}
}
private void btnSteganografie_Click(object sender, EventArgs e)
{
byte[] arImage = imageToByteArray(Image.FromFile(txtFile.Text));
string input = txtText.Text;
string inputInBits = GetBits(input);
char[] bits = inputInBits.ToCharArray();
int i = 0;
for (i = 54; (i < arImage.Length & i < bits.Length+54); i++)
{
if ((int)arImage[i] == 0)
{
arImage[i] = (byte)2;
}
if ((int)arImage[i] == 255)
{
byte bBit = new byte();
bBit = 2;
arImage[i] = (byte)(arImage[i]-bBit);
}
int lastBit = ((int)arImage[i]) % 2;
int dataBit = ((int)bits[i - 54])%2;
if (lastBit != dataBit)
{
arImage[i]++;
}
}
arImage[i] = 0;
Image result = byteArrayToImage(arImage);
picEncoded.Image = result;
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
result.Save(sfd.FileName+".bmp",System.Drawing.Imaging.ImageFormat.Bmp);
}
}
public string GetBits(string input)
{
StringBuilder sbBuilder = new StringBuilder();
byte[] bytes = Encoding.Unicode.GetBytes(input);
foreach (byte bByte in Encoding.Unicode.GetBytes(input))
{
int iByte = (int)bByte;
for (int i = 7; i >= 0 & (iByte!=0 | i!=7); i--)
{
if (iByte - Math.Pow(2, i) >= 0)
{
sbBuilder.Append("1");
iByte -= (int)Math.Pow(2, i);
}
else
{
sbBuilder.Append("0");
}
}
}
return sbBuilder.ToString();
}
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
//**********ERROR HAPPENS HERE *************
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
byte[] arImageTEST = imageToByteArray(returnImage);
//**********byteArrayIn should be the same as arImageTEST ***********
return returnImage;
}
}
Maybe it has something to do with this information available here:
You must keep the stream open for the
lifetime of the Image.
Hope it helps.

How can I prompt a user to choose a location to save a file?

In my main Form I have a method called SavePDFDocument():
private void SavePDFDocument()
{
PDFWrapper pdfWrapper = new PDFWrapper();
pdfWrapper.CreatePDF(horizontalPictureScroller1.GetPictures(), "pdfDocument.pdf");
}
As you can see, right now I'm manually typing in a name for the file. I'd like to ask the user to choose where to save it and what name to give it.
This is the CreatePDF() method I'm using above:
public void CreatePDF(List<System.Drawing.Image> images, string filename)
{
if (images.Count >= 1)
{
Document document = new Document(PageSize.LETTER);
try
{
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
// step 3: we open the document
document.Open();
foreach (var image in images)
{
iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
if (pic.Height > pic.Width)
{
//Maximum height is 800 pixels.
float percentage = 0.0f;
percentage = 700 / pic.Height;
pic.ScalePercent(percentage * 100);
}
else
{
//Maximum width is 600 pixels.
float percentage = 0.0f;
percentage = 540 / pic.Width;
pic.ScalePercent(percentage * 100);
}
pic.Border = iTextSharp.text.Rectangle.BOX;
pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
pic.BorderWidth = 3f;
document.Add(pic);
document.NewPage();
}
}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
// step 5: we close the document
document.Close();
}
}
Any suggestions?
Did you take a look at SaveFileDialog?
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
I believe this page describes what you are looking for:
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
}
A useful link: How to: Save Files Using the SaveFileDialog Component

Categories

Resources