C# Add images and text to PowerPoint slides - c#

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;
}

Related

Can't find a specific Control using Controls.Find()

I'm using Controls.Find() method to find a ListBox that i created dynamically. Name of those ListBoxes come from Directories that i created and named uniquely. Everytime i use this method it says the reference is null. How do i get the actual ListBox that i want?
Here is code:
public DosyaTakipAraci()
{
InitializeComponent();
string anaDizin = Properties.Settings.Default.anaDizin;
if (anaDizin == "" || anaDizin == null)
{
dizinSecici.Description = "Lütfen dosyalarınızın kaydedileceği bir dizin seçiniz.";
dizinSecici.ShowDialog();
Properties.Settings.Default.anaDizin = dizinSecici.SelectedPath + #"\";
Properties.Settings.Default.Save();
}
string[] dizinler = Directory.GetDirectories(anaDizin);
if (dizinler.Length > 0)
DizinleriYukle(dizinler);
}
This method loads all Directories
private void DizinleriYukle(string[] dizinler)
{
for (int i = 0; i < dizinler.GetLength(0); i++)
{
DirectoryInfo dizin = new DirectoryInfo(dizinler[i]);
DizinYukleyici(dizin.Name);
}
}
This method is belongs to Directory icon that is created for each Directory
private void DizinSimge_DragDrop(object sender, DragEventArgs e)
{
string[] dosyalar = (string[])e.Data.GetData(DataFormats.FileDrop);
PictureBox simge = (PictureBox)sender;
string dizinAdi = simge.Name;
string anaDizin = Properties.Settings.Default.anaDizin;
foreach (string dosya in dosyalar)
{
string dosyaAdi = Path.GetFileName(dosya);
if (File.Exists($#"{anaDizin}{dizinAdi}\{dosyaAdi}"))
return;
File.Copy(dosya, $#"{anaDizin}{dizinAdi}\{dosyaAdi}", true);
DosyaYukleyici(Panel.Controls.Find(dizinAdi, true).FirstOrDefault() as ListBox);
}
}
This method loads the Directory and creates Controls related to the Directory
private void DizinYukleyici(string dizinAdi)
{
#region Kontrol tanımları
PictureBox dizinSimge = new PictureBox
{
Name = dizinAdi,
Image = Properties.Resources.folder,
Size = new Size(32, 32),
Location = new Point(this.X, this.Y),
AllowDrop = true
};
TextBox dizinBaslik = new TextBox
{
Name = dizinAdi,
Text = dizinAdi,
Location = new Point(this.X + dizinSimge.Width + 5, this.Y + 8),
Font = new Font("Segou UI", 8.25f),
BackColor = this.BackColor,
BorderStyle = BorderStyle.None,
ReadOnly = true
};
ListBox Dosyalar = new ListBox
{
Name = dizinAdi,
Text = null,
Location = new Point(this.X, this.Y + dizinSimge.Height + 5),
BorderStyle = BorderStyle.None,
BackColor = this.BackColor,
Width = dizinSimge.Width + dizinBaslik.Width + 5
};
#endregion
#region Olaylar
dizinSimge.DragEnter += new DragEventHandler(DizinSimge_DragEnter);
dizinSimge.DragDrop += new DragEventHandler(DizinSimge_DragDrop);
dizinBaslik.DoubleClick += new EventHandler(Baslik_DoubleClick);
dizinBaslik.KeyPress += new KeyPressEventHandler(Baslik_Press);
Dosyalar.DragEnter += new DragEventHandler(DizinSimge_DragEnter);
Dosyalar.DragDrop += new DragEventHandler(Dosyalar_DragDrop);
#endregion
Panel.Controls.Add(dizinSimge);
Panel.Controls.Add(dizinBaslik);
Panel.Controls.Add(Dosyalar);
DosyaYukleyici(Dosyalar);
this.X += (short)(dizinSimge.Width + dizinBaslik.Width + 5);
}
This method Loads files of a Directory and adds them to related ListBox
private void DosyaYukleyici(ListBox Liste)
{
string dizinAdi = Liste.Name;
Liste.Items.Clear();
string anaDizin = Properties.Settings.Default.anaDizin;
string dizin = Path.Combine(anaDizin, dizinAdi);
string[] dosyalar = Directory.GetFiles(dizin);
foreach (string dosya in dosyalar)
{
Liste.Items.Add(Path.GetFileName(dosya));
}
}
You give the PictureBox, the TextBox and the ListBox the same name dizinAdi. Now when you search a ListBox, you may find a PictureBox or a TextBox first. Then you try to cast it with as ListBox which yields null if it is not the ListBox.
Filter the by type:
Panel.Controls.Find(dizinAdi, true).OfType<ListBox>().FirstOrDefault()
alternatively, you could give different names to different controls like
"lst" + dizinAdi
"txt" + dizinAdi
"pic" + dizinAdi
or
dizinAdi + "ListBox"
dizinAdi + "TextBox"
dizinAdi + "PictureBox"

Saving scatter graph as image in C#

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);

Adding table (bottom left) programatically to (0,0,0) in Autocad 2015

This is my program to open an excel table & programmatically create at a mentioned point. When I specify (0,0) it adds top left corner. But I want the bottom left corner. How would be the code ?
This is my program..
[CommandMethod("exl")]
static public void TableFromSpreadsheet()
{
const string dlName = "Excel to Autocad";
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;
var ed = doc.Editor;
var ofd = new OpenFileDialog("Select Excel Spreadsheet to Link", null, "xls; xlsx", "ExcelFileToLink", OpenFileDialog.OpenFileDialogFlags.DoNotTransferRemoteFiles);
var dr = ofd.ShowDialog();
if (dr != System.Windows.Forms.DialogResult.OK)
return;
ed.WriteMessage("\nFile selected was \"{0}\". Contains these sheets:", ofd.Filename);
var sheetNames = GetSheetNames(ofd.Filename);
if (sheetNames.Count == 0)
{
ed.WriteMessage("\nWorkbook doesn't contain any sheets.");
return;
}
for (int i = 0; i < sheetNames.Count; i++)
{
var name = sheetNames[i];
ed.WriteMessage("\n{0} - {1}", i + 1, name);
}
var pio = new PromptIntegerOptions("\nSelect a sheet");
pio.AllowNegative = false;
pio.AllowZero = false;
pio.DefaultValue = 1;
pio.UseDefaultValue = true;
pio.LowerLimit = 1;
pio.UpperLimit = sheetNames.Count;
var pir = ed.GetInteger(pio);
if (pir.Status != PromptStatus.OK)
return;
var ppr = ed.GetPoint("\nEnter table insertion point");
if (ppr.Status != PromptStatus.OK)
return;
var dlm = db.DataLinkManager;
var dlId = dlm.GetDataLink(dlName);
if (dlId != ObjectId.Null)
{
dlm.RemoveDataLink(dlId);
}
var dl = new DataLink();
dl.DataAdapterId = "AcExcel";
dl.Name = dlName;
dl.Description = "Excel 2 Autocad";
dl.ConnectionString = ofd.Filename + "!" + sheetNames[pir.Value - 1];
dl.DataLinkOption = DataLinkOption.PersistCache;
dl.UpdateOption |= (int)UpdateOption.AllowSourceUpdate;
dlId = dlm.AddDataLink(dl);
using (var tr = doc.TransactionManager.StartTransaction())
{
tr.AddNewlyCreatedDBObject(dl, true);
var bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
var tb = new Table();
tb.TableStyle = db.Tablestyle;
tb.Position = ppr.Value;
tb.Cells.SetDataLink(dlId, true);
tb.GenerateLayout();
var btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
btr.AppendEntity(tb);
tr.AddNewlyCreatedDBObject(tb, true);
tr.Commit();
}
}
You may try something like this Extension method (didn't have more time to test it...)
/// <summary>
/// Recalculate the position for a bottom left coordinate.
/// Must be called after GenerateLayout().
/// </summary>
/// <param name="tbl">Table object</param>
/// <param name="bottomLeft">Bottom Left desired position</param>
public static void MoveToBottomLeft(this Table tbl, Point3d bottomLeft)
{
Point3d maxPoint = tbl.Bounds.Value.MaxPoint; // this is the bottom left (min point)
Point3d topLeft = new Point3d(maxPoint.Y, bottomLeft.Y, bottomLeft.Z); // this should be topLeft
Point3d newPosition = bottomLeft.TransformBy(Matrix3d.Displacement(bottomLeft.GetVectorTo(newPosition))); // move bottomLeft to newPosition
tbl.Position = newPosition; // apply the new position
}

The type or namespace name 'Neodynamic' could not be found (are you missing a using directive or an assembly reference?)

i want to use the neodynamic image draw sdk and keep getting this error on build i have searched for solutions but none work i have this is my current code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevPro.Data.Enums;
using YGOPro_Launcher.CardDatabase;
using System.IO;
using System.Reflection;
using System.Data.SQLite;
using DevPro_CardManager.Properties;
using Neodynamic.SDK;
namespace Outlaws_CardManager
{
public partial class cardmaker : Form
{
public cardmaker()
{
InitializeComponent();
TopLevel = false;
Dock = DockStyle.Fill;
Visible = true;
}
private void GenerateCard()
{
//Get the info to create the card
string cardname = "";
string cardid = "";
string level = "";
string race = "";
string attribute = "";
string atk = "";
string def = "";
string type1 = "";
string type2 = "";
string stype = "";
string traptype = "";
string mainpicture = "";
string layout = "Left";
if (!String.IsNullOrEmpty(CardName.Text))
{
cardname = CardName.Text;
}
if (!String.IsNullOrEmpty(CardID.Text))
{
cardid = CardID.Text;
}
if (!String.IsNullOrEmpty(ATK.Text))
{
atk = ATK.Text;
}
if (!String.IsNullOrEmpty(DEF.Text))
{
def = DEF.Text;
}
ImageDraw imgDraw = new ImageDraw();
//Basic settings for Card
imgDraw.Canvas.AutoSize = false;
imgDraw.ImageFormat = ImageDrawFormat.Png;
//Set card size
imgDraw.Canvas.Width = 400;
imgDraw.Canvas.Height = 250;
//Create main decorative shape element
RectangleShapeElement rect1 = new RectangleShapeElement();
rect1.X = 10;
rect1.Y = 10;
rect1.Width = 380;
rect1.Height = 230;
rect1.Roundness = 20;
rect1.StrokeWidth = 0;
//Set background
rect1.Fill.BackgroundColor = Color.Black;
//Add element to output image
imgDraw.Elements.Add(rect1);
//Create top decorative shape element
RectangleShapeElement rect2 = new RectangleShapeElement();
rect2.X = 20;
rect2.Y = 20;
rect2.Width = 360;
rect2.Height = 170;
rect2.Roundness = 10;
rect2.StrokeWidth = 0;
rect2.Fill.BackgroundColor = Color.White;
//Add element to output image
imgDraw.Elements.Add(rect2);
//Create bottom decorative shape element
RectangleShapeElement rect3 = new RectangleShapeElement();
rect3.X = 30;
rect3.Y = 130;
rect3.Width = 340;
rect3.Height = 100;
rect3.Roundness = 10;
rect3.StrokeWidth = 1;
rect3.StrokeFill.BackgroundColor = Color.Black;
rect3.Fill.BackgroundColor = Color.White;
//Add element to output image
imgDraw.Elements.Add(rect3);
//Create an ImageElement to wrap the user logo
if (mainpicture.Length > 0 && System.IO.File.Exists(mainpicture))
{
ImageElement imgElemLogo = new ImageElement();
//Get user logo from disk
imgElemLogo.Source = ImageSource.File;
imgElemLogo.SourceFile = mainpicture;
//Logo Layout
if (layout == "Right")
{
imgElemLogo.X = 40;
imgElemLogo.Y = 40;
}
else
{
imgElemLogo.X = 400 - (50 + 40); //Canvas Width - (Logo Width + X Margin)
imgElemLogo.Y = 40;
}
//Apply Resize logo
Resize resizeLogo = new Resize();
resizeLogo.Width = 50;
resizeLogo.LockAspectRatio = LockAspectRatio.WidthBased;
imgElemLogo.Actions.Clear();
imgElemLogo.Actions.Add(resizeLogo);
//Add element to output image
imgDraw.Elements.Add(imgElemLogo);
}
//Create TextElement objects for each fields
if (cardname.Length > 0)
{
TextElement txtElemName = new TextElement();
txtElemName.AutoSize = false;
txtElemName.Font.Name = "Arial";
txtElemName.Font.Size = 14f;
txtElemName.Font.Unit = FontUnit.Point;
txtElemName.Font.Bold = true;
txtElemName.ForeColor = System.Drawing.Color.Black;
txtElemName.Text = cardname;
txtElemName.TextQuality = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
txtElemName.X = 40;
txtElemName.Y = 40;
txtElemName.Width = 320;
txtElemName.Height = 20;
if (layout == "Left")
{
txtElemName.TextAlignment = ContentAlignment.MiddleLeft;
}
else
{
txtElemName.TextAlignment = ContentAlignment.MiddleRight;
}
//Add element to output image
imgDraw.Elements.Add(txtElemName);
}
if (cardid.Length > 0)
{
TextElement txtElemJob = new TextElement();
txtElemJob.AutoSize = false;
txtElemJob.Font.Name = "Arial";
txtElemJob.Font.Size = 10f;
txtElemJob.Font.Unit = FontUnit.Point;
txtElemJob.ForeColor = System.Drawing.Color.Black;
txtElemJob.Text = cardid;
txtElemJob.TextQuality = System.Drawing.Text.TextRenderingHint.AntiAlias;
txtElemJob.X = 40;
txtElemJob.Y = 64;
txtElemJob.Width = 320;
txtElemJob.Height = 14;
if (layout == "Left")
{
txtElemJob.TextAlignment = ContentAlignment.MiddleLeft;
}
else
{
txtElemJob.TextAlignment = ContentAlignment.MiddleRight;
}
//Add element to output image
imgDraw.Elements.Add(txtElemJob);
}
if (atk.Length > 0)
{
TextElement txtElemAddress = new TextElement();
txtElemAddress.AutoSize = false;
txtElemAddress.Font.Name = "Times New Roman";
txtElemAddress.Font.Italic = true;
txtElemAddress.Font.Size = 11f;
txtElemAddress.Font.Unit = FontUnit.Point;
txtElemAddress.ForeColor = System.Drawing.Color.Black;
txtElemAddress.Text = atk + "\n" + race;
txtElemAddress.TextQuality = System.Drawing.Text.TextRenderingHint.AntiAlias;
txtElemAddress.X = 40;
txtElemAddress.Y = 130;
txtElemAddress.Width = 160;
txtElemAddress.Height = 50;
if (layout == "Left")
{
txtElemAddress.TextAlignment = ContentAlignment.MiddleLeft;
}
else
{
txtElemAddress.TextAlignment = ContentAlignment.MiddleRight;
}
//Add element to output image
imgDraw.Elements.Add(txtElemAddress);
}
if (attribute.Length > 0 || atk.Length > 0)
{
TextElement txtElemPhone = new TextElement();
txtElemPhone.AutoSize = false;
txtElemPhone.Font.Name = "Georgia";
txtElemPhone.Font.Size = 10f;
txtElemPhone.Font.Unit = FontUnit.Point;
txtElemPhone.ForeColor = System.Drawing.Color.Black;
txtElemPhone.Text = "Phone: " + attribute + "\n" + atk;
txtElemPhone.TextQuality = System.Drawing.Text.TextRenderingHint.AntiAlias;
txtElemPhone.X = 200;
txtElemPhone.Y = 180;
txtElemPhone.Width = 160;
txtElemPhone.Height = 50;
if (layout == "Right")
{
txtElemPhone.TextAlignment = ContentAlignment.MiddleLeft;
}
else
{
txtElemPhone.TextAlignment = ContentAlignment.MiddleRight;
}
//Add element to output image
imgDraw.Elements.Add(txtElemPhone);
}
//generate image card and preview it
CardImg.Image = imgDraw.GetOutputImage();
}
}
}
has anyone had a problem like this before please explain how fixed.
Such problems might occur if your Project's Target-Framework and your referenced assembly framework version are incompatible.
So as I may presume, you should take the following steps:
Right-Click on your Project -> Properties -> Target Framework -> Make Sure it is not set on Client Profile and if it does than choose .NET Framework 4 or 4.5 (according to the referenced-assembly targeted FW).
Update: Here is a snapshot of the settings

Face Recognition code using emgu cv and C# and it returns a black image and unknown/unrecognized label all time

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

Categories