In in powerpoint i have placed some diagrams diagrams, where each diagram contains different guid.And i have set the GUID as their hyperlink. when the refresh button is clicked what i do is ,will find the shape and then will get the guid which i have saved as hyperlink for each image , from each image and using that GUID will replace the recent image with the old image in that shape.
foreach (var shape in presentation.Slides[slideno].Shapes)
{
var slide = (PPT.Slide)item;
if (j <= shapeCount)
{
string[] address = new string[] { };
string dskj = slide.Shapes[j].Name;
if (slide.Shapes[j].Name.Equals("DIAGRAM")//, StringComparison.InvariantCultureIgnoreCase)
&& slide.Shapes[j].ActionSettings[PPT.PpMouseActivation.ppMouseClick].Hyperlink.Address != null)
{
address = slide.Shapes[j].ActionSettings[PPT.PpMouseActivation.ppMouseClick].Hyperlink.Address.Split('*');
string Type = address[0];
string Guid = address[1];
if (Type == "D")
{
Session.path = presentation.Path;
if (Session.path != "")
Session.Repository.GetProjectInterface().PutDiagramImageToFile(address[1], Session.path + "\\" + address[1] + ".jpg", 1);
bool diagrm = false;
try
{
EA.Diagram diag = Session.Repository.GetDiagramByGuid(Guid);
diagrm = true;
}
catch
{
continue;
}
if (diagrm)
{
float Shapeleft = slide.Shapes[j].Left;
float Shapetop = slide.Shapes[j].Top;
float Shapewidth = slide.Shapes[j].Width;
float Shapeheight = slide.Shapes[j].Height;
slide.Shapes[j].Delete();
PPT.Shape pic = slide.Shapes.AddPicture(Session.path + "\\" + Guid + ".jpg", Microsoft.Office.Core.MsoTriState.msoFalse,
Microsoft.Office.Core.MsoTriState.msoTrue, Shapeleft, Shapetop, Shapewidth, Shapeheight);
pic.Name = "DIAGRAM";
pic.ActionSettings[PPT.PpMouseActivation.ppMouseClick].Hyperlink.Address = "D*" + Guid;
}
}
}
}
using this above code everything works great.
address = slide.Shapes[j].ActionSettings[PPT.PpMouseActivation.ppMouseClick].Hyperlink.Address
in address i will get the hyperlink address of that current image,but now my problem is if i have two images in a same single slide , then both the time when it loops inside the shapes it only gives the same hyperlink for both the images.
**NOTE:**If i have only one image in a slide then everything works properly.
Its because you're deleting the previous shape and inserting a new shape at the same place , but each shape contains a ZOrderPosition , where because of you deleted the previous and inserted a new shape the Zorderposition get changed for the new shape and it will be included in the next iteration.So if more than one image is inserted in a shape it only refrsh some images .
SOLUTION:
After deleting the existing and when inserting a new shape set its ZorderPosition also.
pic.ZOrder(MsoZOrderCmd.msoSendToBack);
Hope it works..!!
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;
}
How to add watermark image while uploading image in asp.net mvc.
I am using jquery.uploadfile.min.js multiple file upload for uploading image.
Want to add automatically stored logo image (watermark) to append in my image file that i am going to upload.
IN VIEW:
var errorOccured = false;
$(function () {
var uploadObj = $("#multipleupload").uploadFile({
url: "./Handler.ashx",
multiple: true,
fileName: "myfile",
maxFileSize: 1024 * 5000,
allowedTypes: "jpg,jpeg,gif,png",
autoSubmit: false,
formData: { "FunctionName": "UploadProductImage", "ProductID": '#clsEncrypt.Encrypt(ViewBag.ProductID.ToString())' }, //"ImgResizeOption": ImgResizeOption
afterUploadAll: function () {
if (!errorOccured) {
window.location.href = 'ProductImage?Product=#(clsEncrypt.Encrypt(ViewBag.ProductID.ToString()))';
}
},
onError: function (files, status, errMsg) {
alert('file(s) could not be uploaded. Error: ' + errMsg);
errorOccured = true;
}
});
$("#startUpload").click(function () {
uploadObj.startUpload();
});
});
IN HANDLER :
public void UploadProductImage()
{
int ProductID = Convert.ToInt32(clsEncrypt.Decrypt(HttpContext.Current.Request["ProductID"]));
string PhysicalFolderPath = "~/Images/Product/";
for (int j = 0; j < HttpContext.Current.Request.Files.Count; j++)
{
HttpPostedFile uploadFile = HttpContext.Current.Request.Files[j];
string extention = System.IO.Path.GetExtension(uploadFile.FileName);
UploadPic(uploadFile, j++, PhysicalFolderPath, ProductID);
}
}
protected void UploadPic(HttpPostedFile FUPhoto, int sort, string RemotePath, int ProductID)
{
if (FUPhoto.FileName != "")
{
string ImgUploadResponse = "";
string strExt = Path.GetExtension(FUPhoto.FileName).Trim().ToLower();
string ImageName = DateTime.Now.ToFileTimeUtc() + strExt;
string OriginalImageFullPath = "~/Images/Product/" + ImageName;
if (Directory.Exists(HttpContext.Current.Server.MapPath("~/Images/Product/")).Equals(false))
Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Images/Product/"));
FUPhoto.SaveAs(HttpContext.Current.Server.MapPath(OriginalImageFullPath));
ProductImageEntity objProdImage = new ProductImageEntity();
objProdImage.ProductID = ProductID;
if (ImgUploadResponse != "")
objProdImage.Image = "";
else
objProdImage.Image = ImageName;
if (!String.IsNullOrEmpty(objProdImage.Image))
new ProductImageBLL().InsertUpdateProductImage(objProdImage);
}
}
Please refer the below code for watermark logo to add from code side.
using (Image image = Image.FromFile(#"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"))
using (Image watermarkImage = Image.FromFile(#"C:\Users\Public\Pictures\Sample Pictures\watermark.png"))
using (Graphics imageGraphics = Graphics.FromImage(image))
using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))
{
int x = (image.Width / 2 - watermarkImage.Width / 2);
int y = (image.Height / 2 - watermarkImage.Height / 2);
watermarkBrush.TranslateTransform(x, y);
imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width+1, watermarkImage.Height)));
image.Save(#"C:\Users\Public\Pictures\Sample Pictures\Desert_watermark.jpg");
}
I have installed and tried your dll. Everything is good but one issue. The watermark text is added vertically to vertical images (images whose height is bigger than width). Better solution is to add watermark in a horizantal line to vertical images as well as horizantal images. Thanks anyway.
--Edit--
I have solved the problem within this code, which checks and changes the orientation of the image in need. (uploadedImage is the image that i read from stream)
if (uploadedImage.PropertyIdList.Contains(0x0112))
{
PropertyItem propOrientation = uploadedImage.GetPropertyItem(0x0112);
short orientation = BitConverter.ToInt16(propOrientation.Value, 0);
if (orientation == 6)
{
uploadedImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
else if (orientation == 8)
{
uploadedImage.RotateFlip(RotateFlipType.Rotate270FlipNone);
}
else
{
// Do nothing
}
}
Recently I've published a nugget package that do add image water mark with control over opacity and target spot to place the watermark in. Additionally you can add text watermark and do image crop/resize as well.
install via nugget:
Install-Package LazZiya.ImageResize
then you can use the code as below:
//get image from local path
var img = Image.FromFile("wwwroot\\images\\lum3n-358833-unsplash.jpg");
//scale and crop, 600x250 center focus
var newImg = ImageResize.ScaleAndCrop(img, 600, 250, TargetSpot.Center);
//watermark image path
var imgWatermark = "wwwroot\\images\\icon.png";
//add image watermark
newImg.ImageWatermark(imgWatermark,
TargetSpot.TopRight, //define target spot
10, //margin
37); //opacity (0-100)
//save new image
newImg.SaveAs("wwwroot\\images\\600x250-image-watermark.jpg");
//dispose to free up memory
img.Dispose();
newImg.Dispose();
[UPDATE]
The package is updated and some methods has been changed, and better support for more image formats is available (including animated gif).
See the docs for more details.
see live demo page.
i am working in wpf richtextbox.use the below function use for page up.
TextRange range10 = new TextRange(txtAppendValue.CaretPosition.GetLineStartPosition(1), txtptrCaret);
FrameworkContentElement fce1 = (range10.End.Parent as FrameworkContentElement);
if (fce1 != null)
{
fce1.BringIntoView();
range10 = null;
fce1 = null;
}
its working.After i clear the richtextbox and load some other content,at that time the content shown where the pageup happened in last time?how to clear when i reload the document.
Updated:
public void HideTopBorder()
{
TextPointer currentline = txtAppendValue.CaretPosition.GetLineStartPosition(1);
System.Windows.Rect rc = currentline.GetCharacterRect(LogicalDirection.Forward);
System.Windows.Point upperLeftCorner = rc.Location;
HitTestResult result = VisualTreeHelper.HitTest(txtAppendValue, upperLeftCorner);
if (result == null)
{
Thickness margin = txtAppendValue.Margin;
margin.Top = -20;
txtAppendValue.Margin = margin;
currentline = null;
}
else
{
currentline = null;
}
}
After the result null only pageup happened.at that time i clear the document and load an another document.But now show the richtextbox where the already panned point.not top of the document.
Regards
Arjun
Before you load a new document save the value of rtb.VerticalOffset. Then load the new document and reassign the stored value to rtb.VerticalOffset.
Is there any way to determine if two images are identical?
I want to change an image every time my timer ticks (animation).
But, I need to see which image is displaying, so is there any way to compare 2 images
to do what I want?
if (myImage.Flags == (Image.FromFile(#"Images/Enemy.png").Flags))
{
myImage = Image.FromFile(#"Images/Enemy2.png");
}
else
{
myImage = Image.FromFile(#"Images/Enemy.png");
}
Don't compare the images, just maintain the index of the current image in a variable.
Here's an example that works for any number of images:
private int _currentImageIndex;
private string[] _imagePaths =
{
"Images/Enemy.png",
"Images/Enemy2.png",
"Images/Enemy3.png",
};
...
void NextImage()
{
// Dispose the current image
Image img = pictureBox1.Image;
pictureBox1.Image = null;
if (img != null)
img.Dispose();
// Show the next image
_currentImageIndex = (_currentImageIndex + 1) % _imagePaths.Length;
string path = _imagePaths[_currentImageIndex];
pictureBox1.Image = Image.FromFile(path);
}
I'd try to compare ImageLocation. Although it doesn't work if you have your pictures as resources.
if (PictureBox1.ImageLocation == PictureBox2.ImageLocation)
{
}
See my question:
Dynamically changing image in a picturebox
Here goes simple answer.
In case of just 2 images, use flag
// field, true if enemy2.png is loaded
bool _image2;
// somewhere
if(_image2)
{
myImage = Image.FromFile(#"Images/Enemy.png");
_image2 = false;
}
else
{
myImage = Image.FromFile(#"Images/Enemy2.png");
_image2 = true;
}
I was working on Face Recognition project. After training the database and calling EigenObjectRecognizer, the result is a black image with unrecognized label.When the code runs, it looks like the following http://www.mediafire.com/view/?ewns4iqvd51adsc .And as shown in the picture the detected and supposed to be recognized and extracted face in the image box is totally black. And the input image for recognition is exactly the same as the one the database is trained with.So why it has kept giving Unknown or Unrecognized result.
Part of the code looks
Images from the training set loaded as
public FaceRecognizer()
{
InitializeComponent();
//Load faces from the dataset
try
{
ContTrain = ContTrain + 1;
//Load previous trained and labels for each image from the database Here
string NameLabelsinfo = File.ReadAllText(Application.StartupPath +
"/TrainedFaces/TrainedNameLables.txt");
string[] NameLabels = NameLabelsinfo.Split('%');
NumNameLabels = Convert.ToInt16(NameLabels[0]);
string IDLabelsinfo = File.ReadAllText(Application.StartupPath +
"/TrainedFaces/TrainedNameLables.txt");
string[] IDLables = IDLabelsinfo.Split('%');
NumIDLabels = Convert.ToInt16(IDLables[0]);
if (NumNameLabels == NumIDLabels)
{
ContTrain = NumNameLabels;
string LoadFaces;
// Converting the master image to a bitmap
for (int tf = 1; tf < NumNameLabels + 1; tf++)
{
LoadFaces = String.Format("face{0}.bmp", tf);
trainingImages.Add(new Image<Gray, byte>(String.Format("
{0}/TrainedFaces/{1}", Application.StartupPath, LoadFaces)));
IDLabless.Add(IDLables[tf]);
NameLabless.Add(NameLabels[tf]);
}
}
}
catch (Exception e)
{
//Returns the following message if nothing saved in the training set
MessageBox.Show("Nothing in binary database, please add at least a
face(Simply train the prototype with the Add Face Button).", "Triained
faces load",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
The face recognizer method looks like
private void RecognizeFaces()
{
//detect faces from the gray-scale image and store into an array of type
// 'var',i.e 'MCvAvgComp[]'
Image<Gray, byte> grayframe = GetGrayframe();
stringOutput.Add("");
//Assign user-defined Values to parameter variables:
MinNeighbors = int.Parse(comboBoxMinNeigh.Text); // the 3rd parameter
WindowsSize = int.Parse(textBoxWinSiz.Text); // the 5th parameter
ScaleIncreaseRate = Double.Parse(comboBoxScIncRte.Text); //the 2nd
//parameter
//Detect faces from an image and save it to var i.t MCvAcgComp[][]
var faces = grayframe.DetectHaarCascade(haar, ScaleIncreaseRate,
MinNeighbors,
HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
new Size(WindowsSize, WindowsSize))[0];
if (faces.Length > 0 && trainingImages.ToArray().Length != 0)
{
Bitmap ExtractedFace; //empty
ExtFaces = new Image<Gray, byte>[faces.Length];
faceNo = 0;
foreach (var face in faces)
{
// ImageFrame.Draw(face.rect, new Bgr(Color.Green), 3);
//set the size of the empty box(ExtractedFace) which will later
//contain the detected face
ExtractedFace = new Bitmap(face.rect.Width, face.rect.Height);
ExtFaces[faceNo] = new Image<Gray, byte>(ExtractedFace);
ExtFaces[faceNo] = ExtFaces[faceNo].Resize(100, 100,
Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//TermCriteria for face recognition with numbers of trained images
// like maxIteration
MCvTermCriteria termCrit = new MCvTermCriteria(ContTrain, 0.001);
//Eigen face recognizer
EigenObjectRecognizer recognizer = new EigenObjectRecognizer(
trainingImages.ToArray(),
NameLabless.ToArray(),
700,
ref termCrit);
stringOutput[faceNo] = recognizer.Recognize(ExtFaces[faceNo]);
stringOutput.Add("");
faceNo++;
}
pbExtractedFaces.Image = ExtFaces[0].ToBitmap(); //draw the face detected
// in the 0th (gray) channel with blue color
if (stringOutput[0] == "")
{
label1.Text = "Unknown";
label9.Text = "";
}
//Draw the label for each face detected and recognized
else
{
//string[] label = stringOutput[faceNo].Split(',');
label1.Text = "Known";
// for (int i = 0; i < 2; i++)
//{
label9.Text = stringOutput[0];
//label7.Text = label[1];
//}
}
}
if (faceNo == 0)
{
MessageBox.Show("No face detected");
}
else
{
btnNextRec.Enabled = true;
btnPreviousRec.Enabled = true;
}
}
The training set is trained with detected faces as follows
private void saveFaceToDB_Click(object sender, EventArgs e)
{
abd = (Bitmap) pbExtractedFaces.Image;
TrainedFaces = new Image<Gray, byte>(abd);
trainingImages.Add(TrainedFaces);
NameLabless.Add(StudentName.Text);
IDLabless.Add(StudentID.Text);
//Write the number of trained faces in a file text for further load
File.WriteAllText(Application.StartupPath + "/TrainedFaces
/TrainedNameLables.txt", trainingImages.ToArray().Length + "%");
File.WriteAllText(Application.StartupPath + "/TrainedFaces
/TrainedIDLables.txt", trainingImages.ToArray().Length + "%");
//Write the labels of trained faces in a file text for further load
for (int i = 1; i < trainingImages.ToArray().Length + 1; i++)
{
trainingImages.ToArray()[i - 1].Save(String.Format("{0}/TrainedFaces
/face{1}.bmp", Application.StartupPath, i));
File.AppendAllText(Application.StartupPath + "/TrainedFaces
/TrainedIDLables.txt", NameLabless.ToArray()[i - 1] + "%");
File.AppendAllText(Application.StartupPath + "/TrainedFaces
/TrainedNameLables.txt", IDLabless.ToArray()[i - 1] + "%");
}
MessageBox.Show(StudentName.Text + "´s face detected and added :)", "Training
OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Thanks