I'm trying to solve the problem of changing the value PropertyTagImageDescription (0x010E) for the Bitmap object. To add a description for the file. Searching the related topics, and has not found the solution. My use:
Bitmap image = new Bitmap(Image.FromFile(fileName));
var data = System.Text.Encoding.UTF8.GetBytes("My comment");
PropertyItem propItem = image.GetPropertyItem(Convert.ToInt32(0x010E));
propItem.Len = data.Length;
propItem.Value = data;
image.SetPropertyItem(propItem);
But there is an error : "In GDI + error occurred generic."
Help me understand! What I'm doing wrong?
I can't get to your error I haven't found a image that has the 0x010E property set. But I have build a little console application that works:
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
class Program
{
static void Main(string[] args)
{
string imageLocation = #"C:\Users\Jens\Desktop\image.jpg";
string newImageLocation = #"C:\Users\Jens\Desktop\newImage.jpg";
// http://msdn.microsoft.com/en-us/library/ms534415(VS.85).aspx
Int32 ImageDescription = 0x010E;
// get file stream and create Image
using (var fs = new FileStream(imageLocation, FileMode.Open, FileAccess.ReadWrite))
using (var img = Image.FromStream(fs, false, false))
{
var data = Encoding.UTF8.GetBytes("My comment");
// get a property from the image file and use it as container
var propItem = img.PropertyItems.FirstOrDefault();
// set the values that u like to add
// http://msdn.microsoft.com/en-us/library/system.drawing.imaging.propertyitem.aspx
propItem.Type = 2;
propItem.Id = ImageDescription;
propItem.Len = data.Length;
propItem.Value = data;
// add property to Image and save it to the system
img.SetPropertyItem(propItem);
img.Save(newImageLocation);
}
}
}
Related
I´m trying to get an image from PDF with Ghostcript.NET in C#. I have installed Ghostscript dll already (both 32 and 64 bit) and added the reference in the proyect. I´ve just taken the example for the web and it gives me an error (img was null) and i don´t know why. This is the code:
`using System;
using Ghostscript.NET.Rasterizer;
using System.IO;
using Ghostscript.NET;
using System.Drawing.Imaging;
namespace StackOverflowExample
{
class Program
{
static void Main(string[] args)
{
int desired_dpi = 96;
string inputPdfPath = #"C:\Users\orubio\Documents\Pruebas\test.pdf";
string outputPath = #"C:\Users\orubio\Documents\Pruebas\";
GhostscriptVersionInfo gvi = new GhostscriptVersionInfo(#"C:\Program Files (x86)\gs\gs9.56.1\bin\gsdll32.dll");
using (var rasterizer = new GhostscriptRasterizer())
{
rasterizer.Open(inputPdfPath, gvi, false);
for (var pageNumber = 1; pageNumber <= rasterizer.PageCount; pageNumber++)
{
var pageFilePath = Path.Combine(outputPath, string.Format("Page-{0}.png", pageNumber));
var img = rasterizer.GetPage(desired_dpi, pageNumber);
img.Save(pageFilePath, ImageFormat.Png);
Console.WriteLine(pageFilePath);
}
}
}
}
}`
img null error
Ty everyone :D
With that code I can split a multi tiff and save the images to files.
public void SplitImage(string file)
{
Bitmap bitmap = (Bitmap)Image.FromFile(file);
int count = bitmap.GetFrameCount(FrameDimension.Page);
var new_files = file.Split("_");
String new_file = new_files[new_files.Length - 1];
for (int idx = 0; idx < count; idx++)
{
bitmap.SelectActiveFrame(FrameDimension.Page, idx);
bitmap.Save($"C:\\temp\\{idx}-{new_file}", ImageFormat.Tiff);
}
}
here the code for the Pdf creation
public void CreatePDFFromImages(string path_multi_tiff)
{
Image img = new Image(ImageDataFactory.Create(path_multi_tiff));
var p = new Paragraph("Image").Add(img);
var writer = new PdfWriter("C:\\temp\\test.pdf");
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("Images"));
document.Add(p);
document.Close();
Console.WriteLine("Done !");
}
now I would like to save the images to pdf pages and tried it with iText7. But this fails as
using System.Drawing.Imaging;
using Image = iText.Layout.Element.Image;
are to close to have them both in the same class. How could I save the splitted images to PDF pages ? I would like to avoid saving first to files and reloading all the images.
The line
using Image = iText.Layout.Element.Image;
is a so-called using alias directive. It creates the alias Image for the namespace or type iText.Layout.Element.Image. If this poses a problem, you can simply create a different alias. For example
using A = iText.Layout.Element.Image;
will create the alias A for the namespace or type iText.Layout.Element.Image.
my name is omer and i m a student. i created a website and i wnat that the user will upload a video.
i used a ole object to add db and i succed but im having trouble to adding the video from db to the website. i dont want to save the file in folder and than use url. is it posiblle?
the code:
App_Data:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
public class MyVideoHelper
{
public MyVideoHelper()
{
}
//הפונקציה מקבלת מסלול של קובץ ומחזירה את הקובץ מומר לבייטים
public byte[] ConvertFileToByte(Stream file)
{
byte[] video = null;
BinaryReader br = new BinaryReader(file);
video = br.ReadBytes((int)(file.Length));
return video;
}
public FileStream ConvertByteToFile( byte[] file)
{
Stream stream = new MemoryStream(file);
FileStream filestream = stream as FileStream;
return filestream;
}
}
the sapx.cs
MyVideoHelper x = new MyVideoHelper();
string hero3 = Request.Form["hero3"];
if (Session["loggedIn"] != "true")
{
Response.Write("<script>alert('You Are not SignIN!');</script>");
return;
}
if ((video2.PostedFile != null) && (video2.PostedFile.ContentLength > 0))
{
Stream fs = video2.PostedFile.InputStream;
string command = "INSERT INTO videos (hero, file) VALUES( '" + hero3 + "','" + x.ConvertFileToByte(fs) + "')";
MyAdoHelper.DoQuery("omerwatchdb.accdb", command);
}
string sql = "SELECT file FROM videos";
DataTable info = MyAdoHelper.ExecuteDataTable("omerwatchdb.accdb", sql);
string omer;
omer = info.Rows[2][0].ToString();
byte[] bytes = Encoding.ASCII.GetBytes(omer);
vid = x.ConvertByteToFile(bytes);
If you are going to insert a video file into a database (and you should probably not), then you should treat it as binary data, i.e. a BLOB column. To insert data you should use "parameterized query" where specify the data for the SQL command separate from command itself.
you could follow an example on how to add a image file. The process will be identical for a video. And here is an article on how to retrieve the data.
I'm trying to save a copy of the source file directly into a response output stream. But, as a result of this code, the browser window has a dark background. How can I do it without using а MemoryStream?
public static void CreateCollage(IEnumerable<Stamp> stamps, Stream input)
{
using (PdfDocument outDoc = new PdfDocument())
using (PdfDocument inputDoc = PdfReader.Open(input, PdfDocumentOpenMode.Import))
{
for (int i = 0; i < inputDoc.PageCount; i++)
{
var page = inputDoc.Pages[i];
var pageOut = outDoc.AddPage(page);
foreach (var stamp in stamps.Where(s => s.xyp.page == (i + 1)))
InsertData(pageOut, stamp, page.Width.Value, page.Height.Value);
}
outDoc.Save(context.Response.OutputStream, true);
}
}
If I use Save() function - I get an error:
The specified method is not supported.
in System.Web.HttpResponseStream.get_Position()
in PdfSharp.Pdf.IO.PdfWriter.WriteFileHeader(PdfDocument document)
in d:\Users\yudina\Desktop\pdfsharp\PDFsharp\src\PdfSharp\Pdf.IO\PdfWriter.cs:row 488
You do not call outDoc.Close() and nothing ever gets written into your OutputStream.
I'm stuck here while opening and reading csv file in c# program. Ive just started working upon ILNumerics to display 3D matrix graph, but the Exception rises with
"Could not find file 'C:\Users\asd\Documents\Visual Studio 2013\Projects\matrixgraph\martix\bin\Debug\stats.csv'."
Please help me out!
Below is the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using ILNumerics;
using ILNumerics.Drawing;
using ILNumerics.Drawing.Plotting;
namespace martix
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ilPanel1_Load(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
string path = #"C:\Users\asd\Documents\Visual Studio 2013\Projects\matrixgraph\martix\bin\Debug\stats.csv";
StreamReader sr = new StreamReader(File.Open(path, FileMode.Open));
string dataLines = string.Empty;
while (sr.Peek() != -1)
dataLines += sr.ReadLine().Replace(";", ",") + "\n";
sr.Close();
dataLines = dataLines.Trim('\n');
//Convert the data-string into an ILArray
ILArray<int> AN = ILMath.csvread<int>(dataLines);
//Create a new scene, which is the base for our graph
var scene = new ILScene();
using (ILScope.Enter())
{
//Convert all data points to float
ILArray<float> A = ILMath.tosingle(AN);
//Add a plot to the scene and configure it
scene.Add(new ILPlotCube
{
//Render in 3D
TwoDMode = false,
//Add 3 axes
Axes =
{
XAxis =
{
Label = { Text = "Price in $" },
GridMajor =
{
DashStyle = DashStyle.Dashed,
Color = Color.DarkGray,
Width = 1
}
},
YAxis =
{
Label = { Text = "Rating count" },
GridMajor =
{
DashStyle = DashStyle.Dashed,
Color = Color.DarkGray,
Width = 1
}
},
ZAxis =
{
Label = { Text = "Download count" }
}
},
//Add the data points
Children = {
new ILPoints {
Positions = A
},
},
//Set start rotation for 3D rendered graph
Rotation = Matrix4.Rotation(new Vector3(1, 1, 1), 0.5f)
});
}
//Add the scene to the ILPanel
ilPanel1.Scene = scene;
}
}
}
It may be the spaces you have in the path. Nevermind, you're using verbatim string.
Are you sure that path is accessible and is not a networked mapped path? Can you move your file temporarily? It really seems that you don't have access to that path.
Also you should try doing the following to pinpoint the issue:
System.IO.FileInfo fi = null;
try
{
fi = new System.IO.FileInfo(path);
}
catch (ArgumentException) {... }
catch (System.IO.PathTooLongException) {... }
catch (NotSupportedException) {... }
if (ReferenceEquals(fi, null))
{
...
// file name is not valid
}
else
{
...
// file name is valid... May check for existence by calling fi.Exists.
}
EDIT:
use System.IO.Directory.GetFiles to list the exact names of the files in that folder, it may be that the file name is different (stats.csv.csv) and window explorer is hiding the extension.
Got the solution while trying. I created the csv file programatically and this time it read the file.
Just added the few line before the path and modified the path.
StringBuilder csv = new StringBuilder();
csv.AppendLine("112,113,222");
string csvpath = #"C:\\stats\xyz.csv";
File.AppendAllText(csvpath,csv.ToString());
string path = #"C:\stats\xyz.csv";
And thats it. Anyways Thanks for helping :)