How to convert Bitmapdata to Base64 format? - haxe

Is there any example which helps in generating Base64 based image from Bitmapdata?
I know I have to use encode in bitmapdata, but I am not sure how to use it?
It takes (rect : flash.geom.Rectangle, compressor : flash.utils.Object, ?byteArray : flash.utils.ByteArray) : flash.utils.ByteArray;
How to fill compressor incase I want to compress using jpeg?
Also, what's the input of byteArray ?
Any help?

There is an example in the AS3 doc of BitmapData.html#encode():
// Compress a BitmapData object as a JPEG file.
var bitmapData:BitmapData = new BitmapData(640,480,false,0x00FF00);
var byteArray:ByteArray = new ByteArray();
bitmapData.encode(new Rectangle(0,0,640,480), new flash.display.JPEGEncoderOptions(), byteArray);
To generate a Base64 String, you can use haxe.crypto.Base64 (added after 3.0.1).
In OpenFL, ByteArray extends Bytes. So you may simply feed it to Base64.encode.

Related

How do I convert an InputStream into a Map in Groovy?

Suppose I have an InputStream that contains JSON data, and I want to convert it to a Map(Key Value Pairs), so for example I can write that to a log file.
What is the easiest way to take the InputStream and convert it to a Map?
public String convertInputStreamToMap(InputStream isobj) {
// ???
}
I've tried converting to String which works as expected but when the data is really long the data will be incomplete. So I want some easiest way to directly convert this to Map.
Use ObjectMapper from com.fasterxml.jackson.databind to directly convert inputstream to Map:
for example:
objectMapper.readValue(is, Map.class);
there is a built-in class in groovy to parse json: groovy.json.JsonSlurper
it has parse method that accepts almost any source including InputStream
def url = 'https://httpbin.org/get'.toURL()
def json = url.withInputStream{inputStream->
new groovy.json.JsonSlurper().parse(inputStream)
}
println json.headers
and if you want to convert InputStream to String, groovy provides additional methods to work with InputStream class: https://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/InputStream.html
the following code reads the content of this InputStream using specified charset and returns it as a String.
String s = inputStream.getText("UTF-8")

How do I save an svg node to a file using nodejs?

I'm using d3 through a small helper package: https://www.npmjs.com/package/d3-node
I created my svg file using d3-node, here's the code.
const D3Node = require('d3-node')
var d3n = new D3Node()
var svg = d3n.createSVG()
.style("width","1920px")
.style("height","1080px")
.attr("preserveAspectRatio","true")
.html(firstTemplate)
.append("myCustomTag")
Now after this, I have no idea how to save the output. The main problem is in myCustomTag.
console.log(d3n.d3Element.select("svg").node().innerHTML)
This line is supposed to output my svg, and it does, except that myCustomTag becomes mycustomtagand my svg gets corrupt.
I have tried select("svg").node().outerHTML, select("svg").html(), innerText, I just couldn't find anything.
I can't use the innerHTML in this case, is there a way to store the svg file directly from the d3 variable?
You could use xmlserializer since SVG is XML and XML is case sensitive. Something like this works for me:
const D3Node = require('d3-node');
const xmlserializer = require('xmlserializer');
const d3n = new D3Node();
var svg = d3n.createSVG()
.style("width","1920px")
.style("height","1080px")
.attr("preserveAspectRatio","true");
svg.append("myCustomTag");
console.log(xmlserializer.serializeToString(svg.node()));
HTML is not case sensitive so when you try to use HTML methods to serialize things you won't necessarily get what you want.

Decode and unzip a Base64 encoded and Gziped compressed text

I am trying to read a text from XML node. The text is base 64 encrypted and Gzip compressed. I am trying in the following ways:
1. XmlNodeList nodeDebugs = xmlDoc.GetElementsByTagName("Debugs");
2. if (nodeDebugs != null)
3. {
4. for (int i = 0; i < nodeDebugs.Count; i++)
5. {
6. XmlNodeList childNodes = nodeDebugs.Item(i).ChildNodes;
7. String nodeName = childNodes.Item(i).Name;
8. if (nodeName == "Debug")
9. {
10. byte[] compressed = System.Text.Encoding.UTF8.GetBytes(childNodes.Item(i).InnerText.Trim());
11. using (var uncompressed = new MemoryStream())
12. using (var inStream = new MemoryStream(compressed))
13. using (var outStream = new GZipStream(inStream, CompressionMode.Decompress))
14. {
15. outStream .CopyTo(uncompressed);
16. Console.WriteLine(Encoding.UTF8.GetString(uncompressed.ToArray()));
17. }
Getting error at Line no 15, as "the magic number in gzip header is not correct."
Any help to resolve this issue is much appreciated. Thanks a lot in advance.
This is the problem, I suspect:
byte[] compressed = System.Text.Encoding.UTF8.GetBytes(childNodes.Item(i).InnerText.Trim());
You said that your data is compressed and then base64-encoded... but your code doesn't use base64 anywhere, which is a massive warning sign. I suspect you want:
string text = childNodes.Item(i).InnerText.Trim();
byte[] compressed = Convert.FromBase64String(text);
If that doesn't work, you should check each step of the transformation - you should have the same data during encoding and decoding, just in the reverse order. See my blog post about diagnosing reversible data transformations for more details - but hopefully the change above will fix it anyway.

Parse attribute of Media Element

I want to parse url attribute from the XML and show image in image control (the one reffered to by the URL) in listbox from the following feed link: http://feeds.bbci.co.uk/news/rss.xml
My code is:
var ComingNewsFromUri = from rss in XElement.Parse(e.Result).Descendants("item")
select new NewsItems
{
Title = rss.Element("title").Value,
PubDate = rss.Element("pubDate").Value,
Description = rss.Element("description").Value
};
For RSS, I would recommend using SyndicationFeed and SyndicationItem....does all the parsing and converting to objects automatically and brilliantly for you.
http://ryanhayes.net/blog/how-to-build-an-rss-feed-reader-in-windows-phone-7part-i-retrieving-parsing-and-displaying-post-titles/
I have an RSS feed app on the store myself using SyndicationFeed and it is very reliable and convenient.
Here is another sample by Microsoft
http://code.msdn.microsoft.com/wpapps/RSS-Reader-Sample-1702775f

Is there a way to get all embedded objects in .xlsx file using xssf event mdel api

Is there a way to get all embedded objects in .xlsx file using xssf event model api?
Usermodel has the method workbook.getallembedds...similarly is there anything in eventmodel?
This is an example in usermodel.I want to implement the same functionality using eventusermodel.Kindly help.
for (PackagePart pPart : workbook.getAllEmbedds()) {
String contentType = pPart.getContentType();
if (contentType.equals(------)
Instead of xssfworkbook(in usermodel), in the eventmodel code i have a containerObject of type OPCPackage.
#Gagravarr : Thanks for your reply. I tried using the method suggested by you...but im unable to get the contents of the embedded excel.Could you please help me find out where I am going wrong.Here is a part of the code:
ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(container);
XSSFReader xssfReader = new XSSFReader(container);
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator)xssfReader.getSheetsData();
for(PackageRelationship rel : iter.getSheetPart().getRelationshipsByType(XSSFRelation.OLEEMBEDDINGS.getRelation()))
embedds.add(getTargetPart(rel));
for (PackagePart pPart :getAllEmbedds()) {
String contentType = pPart.getContentType();
// Excel Workbook - OpenXML file format
if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml")) {
OPCPackage excelObject = OPCPackage.open(pPart.getInputStream());
`
Your best bet is probably just to enumerate all the package parts, and find the ones that interest you from that
Alternately, the logic to identify embedded parts attached to a given sheet is pretty simple:
List<PackagePart> embedds = new LinkedList<PackagePart>();
// Get the embeddings for the workbook
for(PackageRelationship rel : sheet.getSheetPart().getRelationshipsByType(XSSFRelation.OLEEMBEDDINGS.getRelation()))
embedds.add(getTargetPart(rel));
for(PackageRelationship rel : sheet.getSheetPart().getRelationshipsByType(XSSFRelation.PACKEMBEDDINGS.getRelation()))
embedds.add(getTargetPart(rel));
return embedds;
Finally all I used was this!
ArrayList<PackagePart> parts = container.getParts();
for (PackagePart pPart :parts) {
String contentType = pPart.getContentType();
if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {

Resources