I am using the following method to take screenshots and noticed that all of the screenshot images are not capturing the full window but instead cropping the window. For example I will get a .jpg where I cannot see the entire webpage that is visible on the screen. I suspect that this happens when certain elements are not visible in the DOM and therefore not included in the screenshot. Is this expected behavior? If this is expected, is there a way to program the driver to take a full screen capture with the Selenium 32 bit Internet Explorer Driver consistently? Here is the method I am calling to take the screenshots.
public static void TakeScreenshot(IWebDriver driver, string saveLocation)
{
ITakesScreenshot ssdriver = driver as ITakesScreenshot;
Screenshot screenshot = ssdriver.GetScreenshot();
screenshot.SaveAsFile(saveLocation, ImageFormat.png);
}
Indeed, Richard's answer will work to take a screenshot of the entire current desktop area - if that is what you are after, it will work. If you are actually after having a specific application (e.g. Internet Explorer) that is not 'maximized' while using Selenium, then you might need to take a different approach. Consider forcing the application to be maximized and maybe even have it get focus before taking the screenshot using Richard's method above - or use the Selenium's ITakesScreenshot interface ...
In order to use the System.Windows.Forms namespace in a Console application, you will need to "Add Reference..." to the project. In the Solution Explorer, right-click on "References" and select "Add Reference..."; scroll to System.Windows.Forms, check it and click Okay. After doing that, you will be able to type "using System.Windows.Forms;" at the top of your class file.
This is what I use for capturing the entire screen:
Rectangle bounds = Screen.GetBounds(Point.Empty);
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
bitmap.Save(saveLocation, System.Drawing.Imaging.ImageFormat.Png);
}
the resolution:
Detect if the web page can be display on current browser
If current window screenshot is enough then use screenshot of current browser window
If the current page include scroll bar, then take screen shot of each window by scroll the page accordingly, and cut the screenshot to combine all screenshot together
Put code for whole page screenshot:
using System.Linq;
using System.Threading;
using OpenQA.Selenium;
using DotRez.Utilities.WebDriver;
using System.Drawing;
using System.Drawing.Imaging;
// decide take full screenshot and take current window screenshot according to the height
public static void TakeSnapshot()
{
IJavaScriptExecutor js = Driver as IJavaScriptExecutor;
var fileName = ScenarioContext.Current.ScenarioInfo.Title.ToIdentifier() + DateTime.Now.ToString("HH_mm_ss") + "JS" + ".png";
var fileLocation = Path.Combine(Configuration.SCREEN_SHOT_LOCATION, fileName);
Image finalImage;
// get the full page height and current browser height
string getCurrentBrowserSizeJS =
#"
window.browserHeight = (window.innerHeight || document.body.clientHeight);
window.headerHeight= document.getElementById('site-header').clientHeight;;
window.fullPageHeight = document.body.scrollHeight;
";
js.ExecuteScript(getCurrentBrowserSizeJS);
// * This is async operation. So we have to wait until it is done.
string getSizeHeightJS = #"return window.browserHeight;";
int contentHeight = 0;
while (contentHeight == 0)
{
contentHeight = Convert.ToInt32(js.ExecuteScript(getSizeHeightJS));
if (contentHeight == 0) System.Threading.Thread.Sleep(10);
}
string getContentHeightJS = #"return window.headerHeight;";
int siteHeaderHeight = 0;
while (siteHeaderHeight == 0)
{
siteHeaderHeight = Convert.ToInt32(js.ExecuteScript(getContentHeightJS));
if (siteHeaderHeight == 0) System.Threading.Thread.Sleep(10);
}
string getFullPageHeightJS = #"return window.fullPageHeight";
int fullPageHeight = 0;
while (fullPageHeight == 0)
{
fullPageHeight = Convert.ToInt32(js.ExecuteScript(getFullPageHeightJS));
if (fullPageHeight == 0) System.Threading.Thread.Sleep(10);
}
if (contentHeight == fullPageHeight)
{
TakeSnapshotCurrentPage();
}
else
{
int scollEachHeight = contentHeight - siteHeaderHeight;
int shadowAndBorder = 3;
int scollCount = 0;
int existsIf = (fullPageHeight - siteHeaderHeight) % scollEachHeight;
bool cutIf = true;
if (existsIf == 0)
{
scollCount = (fullPageHeight - siteHeaderHeight) / scollEachHeight;
cutIf = false;
}
else
{
scollCount = (fullPageHeight - siteHeaderHeight) / scollEachHeight + 1;
cutIf = true;
}
// back to top start screenshot
string scollToTopJS = "window.scrollTo(0, 0)";
js.ExecuteScript(scollToTopJS);
Byte[] imageBaseContent = ((ITakesScreenshot)Driver).GetScreenshot().AsByteArray;
Image imageBase;
using (var ms = new MemoryStream(imageBaseContent))
{
imageBase = Image.FromStream(ms);
}
finalImage = imageBase;
string scrollBar = #"window.scrollBy(0, window.browserHeight-window.headerHeight);";
for (int count = 1; count < scollCount; count++)
{
js.ExecuteScript(scrollBar);
Thread.Sleep(500);
Byte[] imageContentAdd = ((ITakesScreenshot)Driver).GetScreenshot().AsByteArray;
Image imageAdd;
using (var msAdd = new MemoryStream(imageContentAdd))
{
imageAdd = Image.FromStream(msAdd);
}
imageAdd.Save(fileLocation, ImageFormat.Png);
Bitmap source = new Bitmap(imageAdd);
int a = imageAdd.Width;
int b = imageAdd.Height - siteHeaderHeight;
PixelFormat c = source.PixelFormat;
// cut the last screen shot if last screesshot override with sencond last one
if ((count == (scollCount - 1)) && cutIf)
{
Bitmap imageAddLastCut =
source.Clone(new System.Drawing.Rectangle(0, contentHeight - existsIf, imageAdd.Width, existsIf), source.PixelFormat);
finalImage = combineImages(finalImage, imageAddLastCut);
source.Dispose();
imageAddLastCut.Dispose();
}
//cut the site header from screenshot
else
{
Bitmap imageAddCutHeader =
source.Clone(new System.Drawing.Rectangle(0, (siteHeaderHeight + shadowAndBorder), imageAdd.Width, (imageAdd.Height - siteHeaderHeight - shadowAndBorder)), source.PixelFormat);
finalImage = combineImages(finalImage, imageAddCutHeader);
source.Dispose();
imageAddCutHeader.Dispose();
}
imageAdd.Dispose();
}
finalImage.Save(fileLocation, ImageFormat.Png);
imageBase.Dispose();
finalImage.Dispose();
}
}
//combine two pictures
public static Bitmap combineImages(Image image1, Image image2)
{
Bitmap bitmap = new Bitmap(image1.Width, image1.Height + image2.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.DrawImage(image1, 0, 0);
g.DrawImage(image2, 0, image1.Height);
}
return bitmap;
}
// take current window screenshot
private static void TakeSnapshotCurrentPage()
{
try
{
var screenshot = ((ITakesScreenshot)Driver).GetScreenshot();
var urlStr = Driver.Url;
var fileName = ScenarioContext.Current.ScenarioInfo.Title.ToIdentifier() + DateTime.Now.ToString("HH_mm_ss") + ".png";
var fileLocation = Path.Combine(Configuration.SCREEN_SHOT_LOCATION, fileName);
if (!Directory.Exists(Configuration.SCREEN_SHOT_LOCATION))
{
Directory.CreateDirectory(Configuration.SCREEN_SHOT_LOCATION);
}
screenshot.SaveAsFile(fileLocation, ScreenshotImageFormat.Png);
Console.WriteLine(urlStr);
Console.WriteLine("SCREENSHOT[{0}]SCREENSHOT", Path.Combine("Screenshots", fileName));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Related
I need to extract images from PDF.
I know that some images are rotated 90 degrees (I checked with online tools).
I'm using this code:
PdfRenderListener:
public class PdfRenderListener : IExtRenderListener
{
// other methods ...
public void RenderImage(ImageRenderInfo renderInfo)
{
try
{
var mtx = renderInfo.GetImageCTM();
var image = renderInfo.GetImage();
var fillColor = renderInfo.GetCurrentFillColor();
var color = Color.FromArgb(fillColor?.RGB ?? Color.Empty.ToArgb());
var fileType = image.GetFileType();
var extension = "." + fileType;
var bytes = image.GetImageAsBytes();
var height = mtx[Matrix.I22];
var width = mtx[Matrix.I11];
// rotated image
if (height == 0 && width == 0)
{
var h = Math.Abs(mtx[Matrix.I12]);
var w = Math.Abs(mtx[Matrix.I21]);
}
// save image
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
When I save images with this code the rotated images are saved with distortion.
I have read this post iText 7 ImageRenderInfo Matrix contains negative height on Even number Pages and mkl answer.
In current transfromation matrix (mtx) I have these values:
0
841.9
0
-595.1
0
0
595.1
0
1
I know image rotated 90 degrees. How can I transform an image to get a normal image?
As #mkl mentioned, the true reason was not in the rotation of the image, but with the applied filter.
I analyzed the pdf file with iText RUPS and found that the image was encoded with a CCITTFaxDecode filter:
RUPS screen
Next, I looked for ways to decode this filter and found these questions
Extracting image from PDF with /CCITTFaxDecode filter.
How to use Bit Miracle LibTiff.Net to write the image to a MemoryStream
I used the BitMiracle.LibTiff.NET library
I wrote this method:
private byte[] DecodeInternal(byte[] rawBytes, int width, int height, int k, int bitsPerComponent)
{
var compression = GetCompression(k);
using var ms = new MemoryStream();
var tms = new TiffStream();
using var tiff = Tiff.ClientOpen("in-memory", "w", ms, tms);
tiff.SetField(TiffTag.IMAGEWIDTH, width);
tiff.SetField(TiffTag.IMAGELENGTH, height);
tiff.SetField(TiffTag.COMPRESSION, compression);
tiff.SetField(TiffTag.BITSPERSAMPLE, bitsPerComponent);
tiff.SetField(TiffTag.SAMPLESPERPIXEL, 1);
var writeResult = tiff.WriteRawStrip(0, rawBytes, rawBytes.Length);
if (writeResult == -1)
{
Console.WriteLine("Decoding error");
}
tiff.CheckpointDirectory();
var decodedBytes = ms.ToArray();
tiff.Close();
return decodedBytes;
}
private Compression GetCompression(int k)
{
return k switch
{
< 0 => Compression.CCITTFAX4,
0 => Compression.CCITTFAX3,
_ => throw new NotImplementedException("K > 0"),
};
}
After decoding and rotating the image, I was able to save a normal image. Thanks everyone for the help.
You can try this. I'm using Itext 7 for java. Here you still need to write your own listener:
public class MyImageRenderListener implements IEventListener {
protected String path;
protected String extension;
public MyImageRenderListener (String path) {
this.path = path;
}
public void eventOccurred(IEventData data, EventType type) {
switch (type) {
case RENDER_IMAGE:
try {
String filename;
FileOutputStream os;
ImageRenderInfo renderInfo = (ImageRenderInfo) data;
PdfImageXObject image = renderInfo.getImage();
if (image == null) {
return;
}
byte[] imageByte = image.getImageBytes(true);
extension = image.identifyImageFileExtension();
filename = String.format(path, image.getPdfObject().getIndirectReference().getObjNumber(), extension);
os = new FileOutputStream(filename);
os.write(imageByte);
os.flush();
os.close();
} catch (com.itextpdf.io.exceptions.IOException | IOException e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
public Set<EventType> getSupportedEvents() {
return null;
}
}
I checked for a pdf with a random rotation angle, and 90 degrees, the resulting picture was obtained without distortion
public void manipulatePdf() throws IOException, SQLException, ParserConfigurationException, SAXException {
PdfDocument pdfDoc = new PdfDocument(new PdfReader("path to pdf"), new PdfWriter(new ByteArrayOutputStream()));
MyImageRenderListener listener = new MyImageRenderListener("path to resulting image");
PdfCanvasProcessor parser = new PdfCanvasProcessor(listener);
for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) {
parser.processPageContent(pdfDoc.getPage(i));
}
pdfDoc.close();
}
i am trying to change the pictureBox.Image during Runtime. I have several Model classes with a picture stored, whenever i click on a MenuStripItem i call the method "ChangePictureBoxImages". Till then there is no error (the pB is invisible!) but once i call the method to make the pB visible i get an Error. The Error code: "An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll".
Research said i should dispose the picturebox and set it to "null", however this does NOT help.
My Code:
using (Image current = BitmapManipulator.EvaluateMesurement(CSV_Name1, max_Rows, max_Col, var.TopImage, var.BitmapToManipulate, pB_ColourScale_Evaluation.Image, var.BitmapToManipulate, var.Filepath, var.FoldID))
{
var.LastEvaluationImage = current;
BitmapManipulator.CombineImagesAndSaveThem_Evaluation(var.TopImage, var.BitmapToManipulate, pB_ColourScale_Evaluation.Image, var.Filepath, var.FoldID); //saves the Files as jpg
if (var.CurrentlyShownToUser) //checks if the MenuStripItem is the active one
{
if (var.LastEvaluationImage == null) { MessageBox.Show("the image is null");} //only for debugging purpose -> does never call
ChangePictureBoxImages();
}
}
and the ChangePictureBoxImages():
public void ChangePictureBoxImages()
{
foreach (Fold fold in FoldExisting)
{
if (fold.FoldID == LastSelectedMenuStripItem_Name) //the clicked item is the last Selected MenuStripItem
{
if (fold.LastEvaluationImage != null)
{
Debug.WriteLine(pB_Evaluation_Bottom.Image.ToString() + " " + fold.LastEvaluationImage.ToString());
pB_Evaluation_Bottom.Image = fold.LastEvaluationImage;
}
pB_Evaluation_Top.Image = fold.TopImage;
}
}
}
There is no error till then, the error appears once i call "pB_Evaluation_Bottom.visible = true". (or if i called the visible method first first the error appears upon changing the Image!) The error also appears upon clicking 2 times on the MenuStripItem. I load the picture from the Class Fold as following:
This will set an image in the fold class, this image will then be manipulated and stored in LastEvaluationImage
private void setTheImages(string PictureToManipulate, string PathToTopImage)
{
try
{
this.BitmapToManipulate_intern = (Image)Image.FromFile(#PictureToManipulate, true);
this.TopImage_intern = (Image)Image.FromFile(#PathToTopImage, true);
}
catch (ArgumentNullException ex)
{
Debug.WriteLine("The BitMap for the manipulation process and the top image is not created.");
}
}
and the LastEvaluationImage where the last picture is stored -> this will be called to be the new pb.Image
private Image LastEvaluationImage_intern;
public Image LastEvaluationImage
{
get
{
return this.LastEvaluationImage_intern;
}
set
{
if (LastEvaluationImage_intern != null) { LastEvaluationImage_intern.Dispose(); LastEvaluationImage_intern = null; }
this.LastEvaluationImage_intern = value;
this.LastEvaluationTime_intern = DateTime.Now;
}
}
I know this is a little complex, but i hope someone can help me.
THANKS IN ADVANCE!
UPDATE: The Error must be in the following Code:
The BitmapManipulator.EvaluateMeasurement Code :
public Image EvaluateMesurement(double[][] MeasuredValues, int max_Rows, int max_Col, Image pB_Evaluation_Top, Image pB_Evaluation_Bottom, Image pB_EvaluationColourScale, Image ManipulatedBitmap, string PathMeasurementFiles, string Foldname)
{
using (Bitmap bitmap = new Bitmap(ManipulatedBitmap))
{
// the data array sizes:
int number_nio = 0;
int number_total = 0;
List<FileInfo> LastFiles;
int got_number_for_trends = Properties.Settings.Default.TrendNumber;
SolidBrush myBrush = new SolidBrush(red);
using (Graphics g = Graphics.FromImage(bitmap))
{
Random rnd = new Random(8);
int[,] data = new int[max_Col, max_Rows];
// scale the tile size:
float sx = 1f * bitmap.Width / data.GetLength(0);
float sy = 1f * bitmap.Height / data.GetLength(1);
LastFiles = FM.GetLastFiles_Trend(ref got_number_for_trends, PathMeasurementFiles);
double[][] CSV_Statistiken = FM.LastFilesToCSV(got_number_for_trends, true, LastFiles, PathMeasurementFiles);
for (int x = 0; x < max_Col; x++)
{
for (int y = max_Rows - 1; y >= 0; y--)
{
number_total++;
RectangleF r = new RectangleF(x * sx, y * sy, sx, sy);
if (MeasuredValues[y][x] < Properties.Settings.Default.Threshhold)
{
number_nio++;
if (CSV_Statistiken[y][x] == Properties.Settings.Default.TrendNumber)
{
myBrush.Color = Color.FromArgb(150, black);
g.FillRectangle(myBrush, r);
}
else
{
myBrush.Color = Color.FromArgb(150, red);
g.FillRectangle(myBrush, r);
}
}
else
{
myBrush.Color = Color.FromArgb(150, green);
g.FillRectangle(myBrush, r);
}
}
}
}
return bitmap;
}
}
This returned bitmap will be stored in fold.LastEvaluationImage as following:
using (Image current = BitmapManipulator.EvaluateMesurement(CSV_Name1, max_Rows, max_Col, var.TopImage, var.BitmapToManipulate, pB_ColourScale_Evaluation.Image, var.BitmapToManipulate, var.Filepath, var.FoldID))
{
var.LastEvaluationImage = current;
}
You're returning a disposed bitmap. It shouldn't be surprising you can't draw something that no longer exists :)
The using (bitmap) is the last thing you want in this case. The bitmap must survive longer than the scope of the using. And the using (current) in the caller has the same problem - you're again disposing the image way too early. You can only dispose it when it's clear that it isn't going to be used ever again - e.g. when you replace it with a new image.
To elaborate, using does nothing but call Dispose when you leave its scope. In the case of Bitmap (which is just a "thin" wrapper around a GDI bitmap), this releases the memory where the actual image data is stored. There isn't anything interesting left, so there's nothing to draw (and you'd basically be calling DrawBitmap(NULL) as far as GDI is concerned).
I have a cropped version of an image that should appear on my screen.
Image 6Island = Image.FromFile("C:\\Users\\6Island.png");
Now the next goal is to Take an image of the screen.
Bitmap CaptureScreen()
{
var image = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
var gfx = Graphics.FromImage(image);
gfx.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
return image;
}
Image 6Island = Image.FromFile("C:\\Users\\6Island.png");
Image currentView = CaptureScreen();
I then want to see if I can I can find the image 6Island inside the new image. And the colors may vary a tiny bit. Is there anyway to do that?
This is just sample quick and dirty and very slow, but it works. This code make a "crop" of your big bitmap and compare it with your small bitmap. If equal then percentage must be 100, if unequal then percentage lower than that. I would say, if bigger than 98%, then you found it.
private static void CompareBigAndSmallBitmaps(string fileName1, string fileName2)
{
var bmpBig = (Bitmap) Image.FromFile(fileName1);
var bmpSmall = (Bitmap) Image.FromFile(fileName2);
for (var offX = 0; offX < bmpBig.Width - bmpSmall.Width; offX++)
{
for (var offY = 0; offY < bmpBig.Height - bmpSmall.Height; offY++)
{
var percentage = CompareSmallBitmaps(bmpBig, bmpSmall, offX, offY);
if (percentage > 98.0) // define percentage of equality
{
// Aha... found something here....and exit here if you want
}
}
}
}
private static double CompareSmallBitmaps(Bitmap bmpBig, Bitmap bmpSmall, int offX, int offY)
{
var equals = 0;
for (var x = 0; x < bmpSmall.Width; x++)
{
for (var y = 0; y < bmpSmall.Height; y++)
{
var color1 = bmpBig.GetPixel(x + offX, y + offY).ToArgb();
var color2 = bmpSmall.GetPixel(x, y).ToArgb();
if (color1 == color2)
{
equals++;
}
}
}
return (Convert.ToDouble(equals)/Convert.ToDouble(bmpSmall.Width*bmpSmall.Height))*100.0;
}
I’m using WinForms. In my form I have a pictureBox and (a From: textbox and a To: Textbox). These textboxes are used to print certain page ranges from a multipage Tif document. The problem is that the application doesn’t print the page ranges. Another problem is that the print preview doesn’t show the correct page, for example If I type number 2 in the From textbox I expect the print preview dialog to show page number 2 from the Tif document, it doesn't show that it shows the wrong page which is page 1.
Test 1: Let’s say if I wanted to print pages 2-5 from the tif document I would type (From: 2 , To: 5).
The weird thing is that the application would only print page 2.
Test 2: I added the line below under print_preview_Setting() and for some reason the print range works using this, but the weird thing is print preview still displays wrong pages.
if (printDialog1.ShowDialog() == DialogResult.OK)
{
currentPrintPage = Convert.ToInt32(From_Pg_txtBox.Text) - 1;
printDocument1.Print();
}
Note: I’ve been printing to PDF for my test cases
Below is a sample Tif Document for Testing
http://www.filedropper.com/tifbordernumberpage
using System.Drawing.Printing;
using System.Drawing.Imaging;
private int currentPrintPage;
private void Form1_Load(object sender, EventArgs e)
{
//using (var dialog = new OpenFileDialog())
//{
// if (dialog.ShowDialog(this) == DialogResult.OK)
// {
// string filename = dialog.FileName;
// pictureBox1.Load(filename);
// }
//}
pictureBox1.Load("C:\\image\\Tif_Document.tif");
}
private void Print_button_Click(object sender, EventArgs e)
{
print_preview_Settings();
// if (printDialog1.ShowDialog() == DialogResult.OK)
// {
// currentPrintPage = Convert.ToInt32(From_Pg_txtBox.Text) - 1;
// printDocument1.Print();
// }
}
private void print_preview_Settings()
{
printPreviewDialog1.Document = printDocument1;
printDocument1.DefaultPageSettings.Margins.Top = 100;
printDocument1.DefaultPageSettings.Margins.Left = 200;
printDocument1.DefaultPageSettings.Margins.Right = 0;
printDocument1.DefaultPageSettings.Margins.Bottom = 0;
currentPrintPage = Convert.ToInt32(From_Pg_txtBox.Text) - 1;
printPreviewDialog1.ShowDialog();
}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
Image i;
i = Image.FromFile("C:\\image\\Tif_Document.tif");
i.SelectActiveFrame(FrameDimension.Page, currentPrintPage);
//Print while maintating aspect ratio of the image
var img_width = e.PageBounds.Width - e.MarginBounds.Left - Math.Abs(e.MarginBounds.Right - e.PageBounds.Width);
var img_height = e.PageBounds.Height - e.MarginBounds.Top - Math.Abs(e.MarginBounds.Bottom - e.PageBounds.Height);
var img = ResizeAcordingToImage(i, img_width, img_height);
e.Graphics.DrawImage(i,
e.MarginBounds.Left, e.MarginBounds.Top, img.Width, img.Height);
currentPrintPage++; //increment page from the Tif doc
if (currentPrintPage < Convert.ToInt32(to_Pg_txtBox.Text))
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
}
private Image ResizeAcordingToImage(Image Source, int boxWidth, int boxHeight)
{
Image resizedImage;
double dbl = (double)Source.Width / (double)Source.Height;
//set height of image to boxHeight and check if resulting width is less than boxWidth,
//else set width of image to boxWidth and calculate new height
if ((int)((double)boxHeight * dbl) <= boxWidth)
{
resizedImage = new Bitmap(Source, (int)((double)boxHeight * dbl), boxHeight);
}
else
{
resizedImage = new Bitmap(Source, boxWidth, (int)((double)boxWidth / dbl));
}
return resizedImage;
}
For some reason, the PrintPage seems to interfere with the active frame of the TIF, so try extracting the image that needs to be displayed:
Image i = Image.FromFile("C:\\image\\Tif_Document.tif");
i.SelectActiveFrame(FrameDimension.Page, currentPrintPage);
using (MemoryStream ms = new MemoryStream()) {
i.Save(ms, ImageFormat.Tiff);
using (Image pageImage = Image.FromStream(ms)) {
var img = ResizeAcordingToImage(pageImage, img_width, img_height);
e.Graphics.DrawImage(pageImage, e.MarginBounds.Left, e.MarginBounds.Top,
img.Width, img.Height);
}
}
I am uploading multiple photos using MultipleFileUpload, if I will upload big size images, then in slider image is not fixed size not showing proper looks. Is there any code for while uploading time restricts the size of images of the gallery.
Below is my c# code:
protected void lnkbtn_Submit_Click(object sender, EventArgs e)
{
try
{
if (MultipleFileUpload.HasFiles)
{
int MaxGalleryId, ReturnValue;
ReturnValue = obj.fnCreateNewPhotoGallery(txtGalleryName.Text, txtGalleryDescrption.Text, DateTime.Now, out MaxGalleryId);
if (ReturnValue != 0)
{
string GalleryPath = System.Configuration.ConfigurationManager.AppSettings["GalleryPath"] + MaxGalleryId;
Directory.CreateDirectory(Server.MapPath(GalleryPath));
string ThumbnailPath = System.Configuration.ConfigurationManager.AppSettings["ThumbnailPath"] + MaxGalleryId;
Directory.CreateDirectory(Server.MapPath(ThumbnailPath));
StringBuilder UploadedFileNames = new StringBuilder();
foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
{
//Upload file
string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
string SaveAsImage = System.IO.Path.Combine(Server.MapPath(GalleryPath + "/"), FileName);
uploadedFile.SaveAs(SaveAsImage);
//Create thumbnail for uploaded file and save thumbnail on disk
Bitmap Thumbnail = CreateThumbnail(SaveAsImage, 200, 200);
string SaveAsThumbnail = System.IO.Path.Combine(Server.MapPath(ThumbnailPath + "/"), FileName);
Thumbnail.Save(SaveAsThumbnail);
}
HTMLHelper.jsAlertAndRedirect(this, "Gallery created successfully. ", "Album.aspx?GalleryId=" + MaxGalleryId);
}
}
}
catch
{
HTMLHelper.jsAlertAndRedirect(this, "Gallery is not created. Some exception occured ", "CreateAlbum.aspx");
}
}
Below is my Create Thumbnail method code :
public Bitmap CreateThumbnail(string ImagePath, int ThumbnailWidth, int ThumbnailHeight)
{
System.Drawing.Bitmap Thumbnail = null;
try
{
Bitmap ImageBMP = new Bitmap(ImagePath);
ImageFormat loFormat = ImageBMP.RawFormat;
decimal lengthRatio;
int ThumbnailNewWidth = 0;
int ThumbnailNewHeight = 0;
decimal ThumbnailRatioWidth;
decimal ThumbnailRatioHeight;
// If the uploaded image is smaller than a thumbnail size the just return it
if (ImageBMP.Width <= ThumbnailWidth && ImageBMP.Height <= ThumbnailHeight)
return ImageBMP;
// Compute best ratio to scale entire image based on larger dimension.
if (ImageBMP.Width > ImageBMP.Height)
{
ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
ThumbnailNewWidth = ThumbnailWidth;
decimal lengthTemp = ImageBMP.Height * lengthRatio;
ThumbnailNewHeight = (int)lengthTemp;
}
else
{
ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
ThumbnailNewHeight = ThumbnailHeight;
decimal lengthTemp = ImageBMP.Width * lengthRatio;
ThumbnailNewWidth = (int)lengthTemp;
}
Thumbnail = new Bitmap(ThumbnailNewWidth, ThumbnailNewHeight);
Graphics g = Graphics.FromImage(Thumbnail);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);
g.DrawImage(ImageBMP, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);
ImageBMP.Dispose();
}
catch
{
return null;
}
return Thumbnail;
}
The above code there is a command line //Upload file from there uploading images. I used this example for the gallery:
http://www.bugdebugzone.com/2013/10/create-dynamic-image-gallery-slideshow.html
You can the ContentLength property of uploadedFile as such:
if (uploadedFile.ContentLength > 1000000)
{
continue;
}
ContentLength is the size in bytes of the uploaded file.
https://msdn.microsoft.com/en-us/library/system.web.httppostedfile.contentlength(v=vs.110).aspx