I am trying to use the memory stream to add an image to a word document. If I get the page from a file everithing works correctly(the commented code). How can I add the same image from the Byte array. I added AddImageToCell( I borrowed the method from the net).
C# WordprocessingDocument - insert an image in a cell
//string imageFile = #"C:\Users\Laptop\Desktop\test.png";
//ImagePart imagePart = document.MainDocumentPart.AddImagePart(ImagePartType.Jpeg);
//using (FileStream stream = new FileStream(imageFile, FileMode.Open))
//{
// imagePart.FeedData(stream);
//}
//AddImageToCell(tc3, document.MainDocumentPart.GetIdOfPart(imagePart));
byte[] signatureTempl = File.ReadAllBytes(#"C:\Users\Laptop\Desktop\test.png");
ImagePart imagePart = document.MainDocumentPart.AddImagePart(ImagePartType.Jpeg);
using (MemoryStream ms = new MemoryStream())
{
using (Bitmap bitmap = new Bitmap())
{
bitmap.Save(ms, ImageFormat.Jpeg);
ms.Position = 0;
imagePart.FeedData(ms);
}
AddImageToCell(tc3, document.MainDocumentPart.GetIdOfPart(imagePart));
}
Related
I am trying to create a pdf with syncfusion and using the example shown on this link:
https://www.syncfusion.com/kb/10673/how-to-create-a-pdf-document-in-aws-lambda
I have created a small console app and I am having issues reading the data on the line with the HELP comment. It is looking for a path rather than reading the string as shown in the example link.
Anyone who has used similar who can suggest a fix? Thanks
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Drawing;
using System.IO;
using System.Text.Json;
using Newtonsoft.Json;
namespace pdf
{
class Program
{
static void Main(string[] args)
{
var result = GetData();
var stream = new StreamReader(result); //----> How do I read this? HELP
JsonReader reader = new JsonTextReader(stream);
var serilizer = new Newtonsoft.Json.JsonSerializer();
var responseText = serilizer.Deserialize(reader);
//Convert Base64String into PDF document
byte[] bytes = Convert.FromBase64String(responseText.ToString());
FileStream fileStream = new FileStream("Sample.pdf", FileMode.Create);
BinaryWriter writer = new BinaryWriter(fileStream);
writer.Write(bytes, 0, bytes.Length);
writer.Close();
System.Diagnostics.Process.Start("Sample.pdf");
}
static string GetData()
{
//Create a new PDF document
PdfDocument document = new PdfDocument();
//Add a page to the document
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page
PdfGraphics graphics = page.Graphics;
//Set the standard font
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
//Draw the text
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
string imagePath = Path.GetFullPath(#"Data\logo.png");
//Load the image from the disk
FileStream imageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
PdfBitmap image = new PdfBitmap(imageStream);
//Draw the image
graphics.DrawImage(image, 30, 30, 100, 25);
//Save the document into stream
MemoryStream stream = new MemoryStream();
//Save the PDF document
document.Save(stream);
document.Close();
return (Convert.ToBase64String(stream.ToArray()));
}
}
}
What about returing directly the stream by GetData method and pass the stream to StreamReader.
static Stream GetData()
{
...
// remove return (Convert.ToBase64String(stream.ToArray()));
return stream;
}
i want to get header image form doc file. i use following code it gives me image path but i can't get it
DocumentFormat.OpenXml.Packaging.ImagePart img = header.ImageParts.FirstOrDefault();
string imgpath = img.Uri.OriginalString;
I think your approach didn't work because the doc file is a zip file.
I don't know in which format you need that image, but you can try something like this to retrieve an image object. I updated my answer with an working example hope it helps.
using (var document = WordprocessingDocument.Open("your document path", true))
{
//Get the header
var header = document.MainDocumentPart.HeaderParts.First();
//These are your paragraphs where you can get the headers Text from
var paragraphList = header.Header.Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>();
//Get the imageId
string imgId = header.GetIdOfPart(header.ImageParts.First());
var imageSource=new BitmapImage();
//Get the imageStream
using (var imgStream = ((ImagePart)header.GetPartById(imgId)).GetStream())
{
//Copy stream to BitmapImage
using (var memoryStream = new MemoryStream())
{
imgStream.CopyTo(memoryStream);
memoryStream.Position = 0;
imageSource.BeginInit();
imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
imageSource.CacheOption = BitmapCacheOption.OnLoad;
imageSource.UriSource = null;
imageSource.StreamSource = memoryStream;
imageSource.EndInit();
}
imageSource.Freeze();
//Save BitmapImage to file
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imageSource));
using (var stream = new FileStream("your path for the image.png", FileMode.Create))
encoder.Save(stream);
}
}
and this is an example how you can get position of your picture, but keep in mind it will only work if your picture got an absolute position.
List<DocumentFormat.OpenXml.Wordprocessing.Drawing> sdtElementDrawing =
header.Header.Descendants<DocumentFormat.OpenXml.Wordprocessing.Drawing>().ToList();
var distL= sdtElementDrawing.First().Anchor.DistanceFromLeft;
I need to convert a byte[] to an Image, but I cannot make it work in C#. If I save the bytearray to a file like this:
using (System.IO.FileStream fs = System.IO.File.Create("test.jpg"))
{
fs.Write(bytearray, 0, (int)lenght);
fs.Close();
}
And test.jpg shows properly. But when I try to make Image from the bytearray like this:
MemoryStream ms = new MemoryStream(bytearray);
pictureBox1.Image = Image.FromStream(ms);
It shows only black box.
I guess one problem is since you are creating test.jpg, it doesn't have any data and so the bytearray is empty.
Do something like :-
byte[] fileData = null;
using (var fs = new FileStream("C:\\1\\roses.jpg", FileMode.Open, FileAccess.Read))
{
var totalLength = (int)fs.Length;
using (var binaryReader = new BinaryReader(fs))
{
fileData = new byte[totalLength];
fs.Read(fileData, 0, totalLength);
fs.Close();
}
MemoryStream ms = new MemoryStream(fileData);
pictureBox1.Image = Image.FromStream(ms);
}
Okay, all was my bad. The code is correct, but the reason why it was showing only black screen was, becuase the picture was so big and it was black in the corners. And the pictureBox was not resizing it or anything so it showed its top right corner only.
I've searched here for help with this, but nothing quite matches what I need. I have an image that gets uploaded, and I'd like to change the size before it gets saved to azure.
So currently my code is:
public ActionResult UserDetails(HttpPostedFileBase photo)
{ var inputFile = new Photo()
{
FileName = photo.FileName,
Data = () => photo.InputStream
};
//then I save to Azure
How would I change the photo.InputStream to 100x 100 px for example?
Here is how I do it:
byte[] imageBytes;
//Of course image bytes is set to the bytearray of your image
using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
using (Image img = Image.FromStream(ms))
{
int h = 100;
int w = 100;
using (Bitmap b = new Bitmap(img, new Size(w,h)))
{
using (MemoryStream ms2 = new MemoryStream())
{
b.Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
imageBytes = ms2.ToArray();
}
}
}
}
From there, I use a MemoryStream to upload. I use blob storage and use the UploadFromStreamAsync to load to blob.
This is a basic view of it.
I am copying all images from my device to directory. While copying the images I am getting this error Operation not permitted on IsolatedStorageFileStream.
Here is my code to copy the files.
MediaLibrary m = new MediaLibrary();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.DirectoryExists("ImagesZipFolder"))
{
deleteFileFolder("ImagesZipFolder");
}
if (!store.DirectoryExists("ImagesZipFolder"))
{
store.CreateDirectory("ImagesZipFolder");
foreach (var picture in m.Pictures)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"ImagesZipFolder/" + picture.Name, FileMode.CreateNew, store))
{
BitmapImage image = new BitmapImage();
image.SetSource(picture.GetImage());
byte[] bytes = ConvertToBytes(image);
stream.Write(bytes, 0, bytes.Length);
}
}
}
}
Here is my ConvertToBytes method.
public byte[] ConvertToBytes(BitmapImage bitmapImage)
{
byte[] data = null;
WriteableBitmap wBitmap = null;
using (MemoryStream stream = new MemoryStream())
{
wBitmap = new WriteableBitmap(bitmapImage);
wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
//data = stream.GetBuffer();
data = stream.ToArray();
DisposeImage(bitmapImage);
return data;
}
}
Basically what I am trying is to create a zip file of all images. I have total 222 images in my device. So how can I solve this issue ? How can I create a zip of this images?
Most probably this is due to the concurrent access to the file
you can refer to the link:
Operation not permitted on IsolatedStorageFileStream. error
I checked your code and it seems to be working (providing there's no error in DisposeImage() method) There is no OperationNotPermittedException occuring. However, if there is error in your code, then it can only be because of deleteFileFolder("ImagesZipFolder") line. Can you give me the snippet so that I can study it further. I m posting the working code... I have replaced that method with simple predefined one--
MediaLibrary m = new MediaLibrary();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.DirectoryExists("ImagesZipFolder"))
{
store.DeleteDirectory("ImagesZipFolder");
}
if (!store.DirectoryExists("ImagesZipFolder"))
{
store.CreateDirectory("ImagesZipFolder");
foreach (var picture in m.Pictures)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"ImagesZipFolder/" + picture.Name, FileMode.CreateNew, store))
{
BitmapImage image = new BitmapImage();
image.SetSource(picture.GetImage());
byte[] bytes = ConvertToBytes(image);
stream.Write(bytes, 0, bytes.Length);
}
}
}
}