Loading local image from Isolated Storage to html page - html

There's something strange and wired with the "image path" when using it in html page from IsolatedStorage.
I want to create an html-page, that will be used by app's webBrowser object. So I create an html page in IsolatedStorage and then use this page with webBroswser.Navigate.
Everything works fine except the images.
1) If I create an html page and images at the root of IsolatedStorage, everything works fine, the code <img src="image.png"> works and I can see the image at page page.
2) However, the way of saving pages and images at root is not a good idea in my opinion as I already have a number of directories, used by app there, so, I create a new directory "Html" and save all pages there.
Now, when I open this page I can't see my image. I've tried several variations of src links and still can't find an answer.
What'll be the correct link in <img src=..."> tag, if the hierarchy is:
IsolatedStorage-->Html(folder)-->index.html(file)
(1) IsolatedStorage-->Html(folder)-->image.png(file)
(2) IsolatedStorage-->Html(folder)-->Images(folder)-->image.png(file)
Actually, I thought it would be something like <img src="image.png"> for (1), but I tried several similar versions and none of them worked.

Well, that seems a bit strange:
This method will save the picture to the IsolatedStorage, but won't allow to use it in html img tag:
using (IsolatedStorageFile isopicsFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isopicsFile.FileExists(Constants.HtmlFolderName + "launch.png") == false)
{
Stream yourFilepath = Application.GetResourceStream(new Uri("/someUri/launch.png", UriKind.Relative)).Stream;
BitmapImage b = new BitmapImage();
b.SetSource(yourFilepath);
WriteableBitmap wb = new WriteableBitmap(b);
using (var isoFileStream = isopicsFile.CreateFile(Constants.HtmlFolderName + "launch.png"))
{
var width = wb.PixelWidth;
var height = wb.PixelHeight;
// Theoretically, there may be the problem, as the file extention is png, not jpg
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
}
}
And this one will save the picture and will allow to use it with html tags:
string f = "somePath/launch.png";
StreamResourceInfo sr = Application.GetResourceStream(new Uri(f, UriKind.Relative));
using (BinaryReader br = new BinaryReader(sr.Stream))
{
byte[] data = br.ReadBytes((int)sr.Stream.Length);
string fileName = "launch.png";
string filePath = Constants.HtmlFolderName + fileName;
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoStore.FileExists(filePath))
{
isoStore.DeleteFile(filePath);
}
using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile(filePath)))
{
bw.Write(data);
bw.Close();
}
}
}
Also, in second case, the picture properties must be set to Content + Always Copy.

Related

XSLFHyperLink not working, Link once added causes PPTX to get corrupted

I have some html content which I'm inserting into a pptx slide and persisting the formatting.
I'm using apache POI for this. A base64 gets generated which I later convert to pptx. Up until now I haven't faced any issues. But now hyperlinks are causing problems.
When I just create the hyperlink with method createHyperlink(), it works fine and the PPT gets generated but the link is not set so it doesn't do any action when clicked.
When I set the URL either through setAddress() or linkToUrl() methods, the PPT generated seems corrupted and windows asks me if it can "repair" it. After the repair option, when the PPT opens, the link does not work.
Below is the code I wrote:
Approach 1:
textRun.createHyperlink();
textRun.getHyperlink().linkToUrl("http://poi.apache.org");
Approach 2:
textRun.createHyperlink();
textRun.getHyperlink().setAddress("http://poi.apache.org");
Approach 3:
XSLFHyperlink link = textRun.createHyperlink();
link.setAddress("http://poi.apache.org");
Approach 4:
XSLFHyperlink link = textRun.createHyperlink();
link.linkToUrl("http://poi.apache.org");
None of these approaches work.
Does anyone have any idea regarding this and provide me the right solution?
Not clear where your problem is. For me XSLFHyperlink.setAddress as well as XSLFHyperlink.linkToUrl are working and create usable hyperlinks using current Apache POI version 5.2.3.
Complete example:
import java.io.FileOutputStream;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.sl.usermodel.*;
import java.awt.Rectangle;
public class CreatePPTXTextShapeWithLinkedText {
static XSLFTextParagraph drawRectWithText(XSLFSlide slide, int x, int y, int width, int height, String text) {
XSLFAutoShape shape = slide.createAutoShape();
Rectangle rect = new Rectangle(x, y, width, height);
shape.setAnchor(rect.getBounds2D());
shape.setShapeType(ShapeType.RECT);
shape.setText(text);
shape.setTextDirection(TextShape.TextDirection.HORIZONTAL);
shape.setVerticalAlignment(VerticalAlignment.MIDDLE);
XSLFTextParagraph xslfTextParagraph = shape.getTextParagraphs().get(0);
xslfTextParagraph.setTextAlign(TextParagraph.TextAlign.CENTER);
return xslfTextParagraph;
}
public static void main(String[] args) throws Exception {
SlideShow slideShow = new XMLSlideShow();
XSLFSlide slide = (XSLFSlide)slideShow.createSlide();
XSLFTextParagraph xslfTextParagraph = drawRectWithText(slide, 100, 100, 500, 50, "This is a test text. ");
XSLFTextRun xslfTextRun = xslfTextParagraph.addNewTextRun();
xslfTextRun.setText("This text is linked to Apache POI.");
XSLFHyperlink xslfHyperlink = xslfTextRun.createHyperlink();
xslfHyperlink.setAddress("http://poi.apache.org");
xslfTextRun = xslfTextParagraph.addNewTextRun();
xslfTextRun.setText(" This is a test text again. ");
xslfTextRun = xslfTextParagraph.addNewTextRun();
xslfTextRun.setText("This text is linked to Stackoverflow.");
xslfHyperlink = xslfTextRun.createHyperlink();
xslfHyperlink.linkToUrl("https://stackoverflow.com");
xslfTextRun = xslfTextParagraph.addNewTextRun();
xslfTextRun.setText(" This is a test text again. ");
FileOutputStream out = new FileOutputStream("./CreatePPTXTextShapeWithLinkedText.pptx");
slideShow.write(out);
out.close();
slideShow.close();
}
}
It creates:
Note: To open a hyperlink while editing a presentation, right-click the hyperlink and select Open Hyperlink on the shortcut menu. Only during a slide show hyperlinks will work as you might think they should. See Open a hyperlink. But that's by design in PowerPoint.

Cannot embed images in email with MailKit

This questions has been posed and answered several places on SO, specifically here : Issue with Gmail - Embedded images using MailKit
and handles my exact query, yet the answer doesn't seem to work for my case.
I've tried to build a simple mailer that embeds images in an HTML email, yet in several clients, all images still end up as attachments.
I suspect the fault to be in the way I handle the image attachments (one .gif and several .png) to be:
// Add pictures to embedded resources and replace links to pictures in the message
foreach (string imgpath in ImgPaths)
{
var image = builder.LinkedResources.Add(imgpath);
image.ContentId = MimeUtils.GenerateMessageId();
image.ContentDisposition = new ContentDisposition() { Disposition = ContentDisposition.Inline };
HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
}
builder.HtmlBody = HtmlFormat;
message.Body = builder.ToMessageBody();
I can see from the emails (received in Gmail, for instance), do show that the images are being listed as:
src="images/cid:TPSXHQUDSAU4.JJRKUIEGLTZ5#Loralei"
All images are attached as attachments in both clients I've tried (gmail and roundcube). I've walked through your tutorials and checked out everything here: https://stackoverflow.com/search?q=Mailkit+Embed
Sadly, I just can't seem to find my error. Hopefully #jstedfast could see where I make my mistake?
UPDATE
As mentioned by #jstedfast, the corrected code should be (for my case anyway):
foreach (string imgpath in ImgPaths)
{
var test = Path.GetFileName(imgpath);
var image = builder.LinkedResources.Add(imgpath);
image.ContentId = MimeUtils.GenerateMessageId();
image.ContentDisposition = new ContentDisposition() { Disposition = ContentDisposition.Inline };
//HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
HtmlFormat = HtmlFormat.Replace($"images/{test}", string.Format("cid:{0}", image.ContentId)); //use images/filename
}
This is a great guide to follow too, https://programming.vip/docs/5dac3983f0cd5.html
This looks like the problem:
<img src="images/cid:TPSXHQUDSAU4.JJRKUIEGLTZ5#Loralei" .../>
That needs to be:
<img src="cid:TPSXHQUDSAU4.JJRKUIEGLTZ5#Loralei" .../>
My guess is that in order to fix this, you'd change the following line of code:
HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
to this:
HtmlFormat = HtmlFormat.Replace(imgpath, string.Format("cid:{0}", image.ContentId));
Hope that helps!

JSFL Replace image for library image

Im trying to make a script using JSFL but I have the following problem...
To understand what Im trying to do, first I used a script to export all images in the library, because I need to make a process to all PNG files.
Now I want to reinsert the images on the library.
If I create a new item I lose all references and that's not useful and I have duplicated items.
What I need to do is re-import the image for each item.
I mean, the same I do when a right-click on the library item->properties->Import...
I was trying to use this script but it doesn't work. Anyone can help me?
var folderURI = fl.browseForFolderURL('Select folder where all images should be exported as *.PNG');
var doc = fl.getDocumentDOM();
if(doc)
{
fl.outputPanel.trace("Start");
var library = doc.library;
var allLibItems = library.items;
var item;
var itemName;
for (var i = 0; i<allLibItems.length; ++i)
{
item = allLibItems[i];//only images will be processed
if(item.itemType == "bitmap")
{
itemName = item.name.slice(item.name.lastIndexOf("/")+1,item.name.lastIndexOf("."));
//Find proccesed image on the directory selected before
//and replace the sourceFilePath (I think this is what I need to use a new image but is not working)
item.sourceFilePath = folderURI + "/" + itemName +".png"
//This returns 'false'
fl.outputPanel.trace(library.updateItem(item.name));
//item.sourceFilePath has the old value, I don't understand why it was not changed
fl.outputPanel.trace(folderURI + "/" + itemName +".png" + " = " + item.sourceFilePath);
}
}
}
Finally, I unzipped the FLA file, it's like a zip and I have all images inside, so it's easy to replace them.
The problem that I had first was that images didnt change because in Flash you have an option to compress images when you create the swf, that's why I didnt see any change on the final result. (right click on the image inside the library -> Properties -> Compression)
I used JSFL to iterate all images (like the example above) and set Compression: "Lossless" instead of "Photo (JPG)".
Obviously this is only a good solution for me because Im using an external tool to compress images with a really great resolution and low size.
You can use JSFL to iterate all images and set Compression: "Photo (JPG)" to all images, with the quality that you want, but probably the result will be different.
Regards
try this
doc.importFile(currentFileURI, true, false, false);
doc.library.selectItem(currentFileName);
doc.library.moveToFolder(libraryPath, currentFileName, true);
but if item exists, FLASH show warning dialog

LibTiff.NET append mode bug?

I've started using LibTiff.NET for writing tiff IPTC tags lately and discovered strange behavior on some files that i have here. I'm using sample code that ships with LibTiff.NET binaries, and it works fine with most of the images, but some files are having image data corruption after these lines:
class Program
{
private const TiffTag TIFFTAG_GDAL_METADATA = (TiffTag)42112;
private static Tiff.TiffExtendProc m_parentExtender;
public static void TagExtender(Tiff tif)
{
TiffFieldInfo[] tiffFieldInfo =
{
new TiffFieldInfo(TIFFTAG_GDAL_METADATA, -1, -1, TiffType.ASCII,
FieldBit.Custom, true, false, "GDALMetadata"),
};
tif.MergeFieldInfo(tiffFieldInfo, tiffFieldInfo.Length);
if (m_parentExtender != null)
m_parentExtender(tif);
}
public static void Main(string[] args)
{
// Register the extender callback
// It's a good idea to keep track of the previous tag extender (if any) so that we can call it
// from our extender allowing a chain of customizations to take effect.
m_parentExtender = Tiff.SetTagExtender(TagExtender);
string destFile = #"d:\00000641(tiffed).tif";
File.Copy(#"d:\00000641.tif", destFile);
//Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
using (Tiff image = Tiff.Open(destFile, "a"))
{
// we should rewind to first directory (first image) because of append mode
image.SetDirectory(0);
// set the custom tag
string value = "<GDALMetadata>\n<Item name=\"IMG_GUID\">" +
"817C0168-0688-45CD-B799-CF8C4DE9AB2B</Item>\n<Item" +
" name=\"LAYER_TYPE\" sample=\"0\">athematic</Item>\n</GDALMetadata>";
image.SetField(TIFFTAG_GDAL_METADATA, value);
// rewrites directory saving new tag
image.CheckpointDirectory();
}
// restore previous tag extender
Tiff.SetTagExtender(m_parentExtender);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
After opening i see mostly blank white image or multiple black and white lines instead of text that have been written there (i don't need to read\write tags to produce this behavior). I noticed this happens when image already has a custom tag (console window alerts about it) or one of tags have got 'bad value' (console window in this case says 'vsetfield:%pathToTiffFile%: bad value 0 for "%TagName%" tag').
Original image: http://dl.dropbox.com/u/1476402/00000641.tif
Image after LibTiff.NET: http://dl.dropbox.com/u/1476402/00000641%28tiffed%29.tif
I would be grateful for any help provided.
You probably should not use CheckpointDirectory method for files opened in append mode. Try using RewriteDirectory method instead.
It will rewrite the directory, but instead of place it at it's old
location (as WriteDirectory() would) it will place them at the end of
the file, correcting the pointer from the preceeding directory or file
header to point to it's new location. This is particularly important
in cases where the size of the directory and pointed to data has
grown, so it won’t fit in the space available at the old location.
Note that this will result in the loss of the previously used
directory space.

saving google map to image from a browser component window inside a c# application

I wanted to save the google map into an image from a webpage.
while i was searching for that i got this program.
http://www.codres.de/downloads/gms.exe[^]
besides other alternatives like print screen i wanted to use a program or map api which can save a specified dimension of google map instead of the screen.
i have used browser component in c# for http access and for displaying certain webpages.
I want to know whether there are options to capture the browser screen to image using any c# functionality or even the browser component would have given such options. just a guess.
i would like to have answers, suggestions on how to capture the map with custom dimension and zoom size to an image.
I used this to get captcha Image from the current page, so you can use similar code just amend the imageID to point to the google map image and use this solution for zooming.
public string newsavefunction(WebBrowser webBrowser1)
{
IHTMLDocument2 doc = (IHTMLDocument2)webBrowser1.Document.DomDocument;
IHTMLControlRange imgRange = (IHTMLControlRange)((HTMLBody)doc.body).createControlRange();
string imagename = string.Empty;
try
{
foreach (IHTMLImgElement img in doc.images)
{
imgRange.add((IHTMLControlElement)img);
imgRange.execCommand("Copy", false, null);
using (Bitmap bmp = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap))
{
bmp.Save(#"F:\captchaimages\captchapic.jpg");
}
imagename = img.nameProp;
break;
}
}
catch (System.Exception exp)
{ }
return imagename;
}