Accessing saved image on a Windows Phone - windows-phone

I am creating a camera app for the Windows Phone but when I want to retrieve my saved photo as a BitmapImage, nothing seems to work. I am using IsolatedStorageSettings to save the path of the images as shown below:
Picture p = mediaLibrary.SavePictureToCameraRoll(fileName, e.ImageStream);
if (!settings.Contains("lastImageTaken"))
{
//GetPath() requires using Microsoft.Xna.Framework.Media.PhoneExtensions;
settings.Add("lastImageTaken", p.GetPath());
}
else
{
settings["lastImageTaken"] = p.GetPath();
}
settings.Save();
then once the app starts up, I try to retrieve that last photo taken as shown below:
lastImageTaken = IsolatedStorageSettings.ApplicationSettings["lastImageTaken"] as string;
Uri uri = new System.Uri(lastImageTaken, UriKind.RelativeOrAbsolute);
BitmapImage image = new BitmapImage(uri);
previouseImage.Source = image;
if (image.PixelWidth < 1)
debugText.Text += " FAILED";
I have also tried something like this:
Uri uri = new System.Uri("file:///" + lastImageTaken.Replace("\\", "/"), UriKind.RelativeOrAbsolute);
BitmapImage image = new BitmapImage(uri);
but nothing seems to display the image. The width of to image always is shown as 0 which displays a "FAILED" text on a debug text. lastImageTaken is shown as C:\Data\Users\Public\Camera Roll\SMCA_jpg.jpg
I have also added the capabilities of ID_CAP_MEDIALIB_PHOTO

It seems that you are saving the image to CameraRoll, but trying to retrieve image from IsolatedStorage. Those are two different storage areas, and they are accessed differently.
In order to save an image to IsolatedStorage you need to replace this :
library.SavePictureToCameraRoll(fileName, e.ImageStream);
with this :
using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
{
// Initialize the buffer for 4KB disk pages.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the image to the local folder.
while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
Then access the image the same way you've described in your original post.
Source : http://msdn.microsoft.com/en-us/library/windows/apps/hh202956(v=vs.105).aspx#BKMK_SavingToTheMediaLibraryAndIsolatedStorage

Related

Embed pdf content in pdf layer

I just registered. I try to address the following case:
Given a basic pdf (a simple, single raster image), I want to get to:
Create a pdf (empty initially), in which I create a layer, in which I embed the raster image of the input_pdf, and mark said layer as visible and not_printable.
Are there tools to do it?
Thanks for the tips.
Since you do not specify a language or a library you use, here it is a solution in C#:
// Extract the page content from the source file.
FileStream stream = File.OpenRead("input.pdf");
PDFFile source = new PDFFile(stream);
PDFPageContent pageContent = source.ExtractPageContent(0);
stream.Close();
PDFFixedDocument document = new PDFFixedDocument();
document.OptionalContentProperties = new PDFOptionalContentProperties();
PDFPage page = document.Pages.Add();
// Create an optional content group (layer) for the extracted page content.
PDFOptionalContentGroup ocg = new PDFOptionalContentGroup();
ocg.Name = "Embedded page";
ocg.VisibilityState = PDFOptionalContentGroupVisibilityState.AlwaysVisible;
ocg.PrintState = PDFOptionalContentGroupPrintState.NeverPrint;
// Draw the extracted page content in the layer
page.Canvas.BeginOptionalContentGroup(ocg);
page.Canvas.DrawFormXObject(pageContent, 0, 0, page.Width, page.Height);
page.Canvas.EndOptionalContentGroup();
// Build the display tree for the optional content
PDFOptionalContentDisplayTreeNode ocgNode = new PDFOptionalContentDisplayTreeNode(ocg);
document.OptionalContentProperties.DisplayTree.Nodes.Add(ocgNode);
using (FileStream output = File.Create("EmbedPageAsLayer.pdf"))
{
document.Save(output);
}
The output PDF file is available here: https://github.com/o2solutions/pdf4net/blob/master/GettingStarted/EmbedPageAsLayer/EmbedPageAsLayer.pdf

itext7 html2pdf is not able to render vector images

We have .net Web API to generate pdf based on certain parameters, this pdf will have images in .eps and .ai (vector images). We are using itext7 html2pdf and passing html as string to the method ConvertToPdf but it's not able to recognize those vector images.
Need help to add vector image in pdf to retain the image quality in pdf and the file size should not increase more than 2MB.
Please find code snippet:
public string GenerateHtmlToPdf(string html , string fileName)
{
//generate pdf from html using iText7
try
{
string filePath = WebConfigurationManager.AppSettings["filePath"];
FileStream finalPdfPath = new FileStream(filePath + "\\" + fileName + ".pdf", FileMode.Create);
string finalPath = filePath + fileName + ".pdf";
PdfFontFactory.RegisterDirectory(FONTDIR);
var NewTransportBold = PdfFontFactory.CreateRegisteredFont("NewTransport-Bold", PdfEncodings.IDENTITY_H);
var NewTransportNormal = PdfFontFactory.CreateRegisteredFont("NewTransport-Regular", PdfEncodings.IDENTITY_H);
var NewTransportLight = PdfFontFactory.CreateRegisteredFont("NewTransport-Light", PdfEncodings.IDENTITY_H);
HtmlConverter.ConvertToPdf(html, finalPdfPath);
return finalPath;
}
catch (IOException ex)
{
var exists = File.Exists("File already exist on desktop");
return "file exist";
}
//end
}
As for pdfs, it is not possible to add svg formats.Hence the svg image would have to be added to the document where the html was set separately.For this a NuGet package named Svg is used.
public void AddSVG(string resourceLocator, float x, float y, int page, int scalePresent = 100)
{
var webClient = new WebClient();
MemoryStream memoryFile = new MemoryStream(webClient.DownloadData(resourceLocator));
SvgDocument memorySVGFile = SvgDocument.Open<SvgDocument>(memoryFile);//get the img as svg doc
var imgconv = memorySVGFile.Draw(3000, 3000);
MemoryStream imgStream = new MemoryStream();
imgconv.Save(imgStream, ImageFormat.Png);//convert svg doc in to a png and save in a mem stream
Image img = new Image(ImageDataFactory.Create(imgStream.ToArray())); //create itext image object from byte array
img.SetFixedPosition(page,x, y, 550);
doc.Add(img);
memoryFile.Close();
}
here the string resourceLocator is the path to the svg. And "doc." is the pdf document where the html was converter to a pdf document.

PDFBox_Facing issue while extracting a certain image from the top of each page

Recently I had asked THIS QUESTION to be able to save all the images present in a PDF file on the File System and I was able to save the images successfully.
I tested my code on a lot of pdf files and it ran just fine. But, today I came accross THIS pdf file from where it is not able to extract some images(attached below).
Can anyone please tell me what else I can do to extract these images? Is it even possible to extract them? Are they really images or something else? I would really appreciate the help.
My code(Please ignore the hardcoding as I am still testing this out):
function fn_getAllImages()
{
var strPdf = "C:\\Users\\a614923\\Desktop\\haka\\Work\\2017\\10. October\\31\\test.PDF";
var strout = "C:\\Users\\a614923\\Desktop\\haka\\Work\\2017\\10. October\\31\\Newfolder\\img"
intPage = 2; //for the 2nd page(the image is present in the 2nd page)
var objPdf = JavaClasses.org_apache_pdfbox_pdmodel.PDDocument.load_3(strPdf);
var objPage = objPdf.getDocumentCatalog().getAllPages().get(intPage-1);
var objImages = objPage.getResources().getXObjects().values().toArray();
var objImage, objImgBuffer, objImageFile;
for(var i=0; i<objImages.length; i++)
{
objImage = objImages.items(i);
Log.Message(objImage.toString());
if(aqString.Find(objImage.toString(),"PDXObjectForm",0,false)>0)
{
continue;
}
else
{
objImage.write2file_2(strout+i);
//objImgBuffer = objImage.getRGBImage();
//objImageFile = JavaClasses.java_io.File.newInstance(strout+i+".png");
//JavaClasses.javax_imageio.ImageIO.write(objImgBuffer,"png",objImageFile);
}
}
}
The image in the PDF file which I want to save(the one inside the red box below):

Image Opacity in PdfSharp.NET

I'm using PDFSharp.NET library to watermark a list of PDFs file. Everything works fine, the website has a lot of samples.
http://www.pdfsharp.net/wiki/Graphics-sample.ashx
The last thing I need is to add the Company Logo, which is big, in the middle of the PDF Page.
I can use a PNG, so that areas which are set as transparent do not "cover" the PDF page".
The pdf is not generated using PDFSharp, but is an "Image" PDF.
For this reason, what I need, is, in addition to the transparency, which works, be able some how to set the Image Opacity!
The code to place the image is this one:
XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
XImage image = XImage.FromFile(mypath);
gfx.DrawImage(image, pwidth/2-image.PixelWidth/2, pheight/2 image.PixelHeight/2);
gfx.Dispose();
Anyone has already faced with that?
I don't know how to alter the opacity of an image while drawing it using PDFsharp (and I'm afraid this can't be done).
So instead I would just open the logo (PNG) with an image processor and set the opacity there.
I was looking in to this aswell now for making a watermark (companyLogo) to place over pdf sheets. The code below lets you change the opacity.
PDFSharp can not change the image opacity. What you can do is change the image you feed to PDF sharp. This has already been answered so I am just sharing my code of doing so.
private void DrawGraphics()
{
XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
Image myTransparenImage = SetImageOpacity(Image.FromFile("MyPath"), (float)opacityYouwant); // opacityYouWant has to be a value between 0.0 and 1.0
XImage image = XImage.FromBitmapSource(Convert(myTransparenImage));
gfx.DrawImage(image, pwidth / 2 - image.PixelWidth / 2, pheight / 2 image.PixelHeight / 2);
gfx.Dispose();
}
public Image SetImageOpacity(Image image, float opacity)
{
try
{
//create a Bitmap the size of the image provided
Bitmap bmp = new Bitmap(image.Width, image.Height);
//create a graphics object from the image
using (Graphics gfx = Graphics.FromImage(bmp))
{
//create a color matrix object
ColorMatrix matrix = new ColorMatrix();
//set the opacity
matrix.Matrix33 = opacity;
//create image attributes
ImageAttributes attributes = new ImageAttributes();
//set the color(opacity) of the image
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
//now draw the image
gfx.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
}
return bmp;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
public BitmapImage Convert(Image img)
{
using (var memory = new MemoryStream())
{
img.Save(memory, ImageFormat.Png);
memory.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
return bitmapImage;
}
}

cannot load image in isolated storage when creating IconicTile

I'm trying to create IconicTile using image saved on isolated storage.
At first, I saved image to isolated storage.
// bitmap is Stream of image source (e.g. from PhotoChooserTask)
var wbmp = new WriteableBitmap(bitmap);
var file = "Shared/ShellContent/IconicTile.png";
// when file exists, delete it
if (storage.FileExists(file))
{
storage.DeleteFile(file);
}
using (var isoFileStream = new IsolatedStorageFileStream(file, FileMode.Create, storage))
{
// use ToolStackPNGWriterExtensions
wbmp.WritePNG(isoFileStream);
}
And I have confirmed PNG file is successfully created using Isostorage Explorer Tools.
Then I try to create IconicTile.
var initialData = new IconicTileData
{
BackgroundColor = SelectedColor,
IconImage = new Uri("isostore:/Shared/ShellContent/IconicTile.png", UriKind.Absolute),
Title = tbTitle.Text,
WideContent1 = tbWideContent1.Text,
WideContent2 = tbWideContent2.Text,
WideContent3 = tbWideContent3.Text
};
var uri = string.Format("/SecondaryPage.xaml");
var TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains(uri));
if (TileToFind == null)
ShellTile.Create(new Uri(uri, UriKind.Relative), initialData, true);
else
TileToFind.Update(initialData);
But image in the created tile are white.
(I'd like to attach image but my reputation is too low. Sorry.)
I tried not only PNG format but also JPG format, but neither doesn't work.
Is there anyway to create IconicTile using image on IsolatedStorage?
The iconic tile format expects a transparent background, based on your comment at the first line (PhotoChooserTask), I suspect you're using some type of image with no transparency.