BASE64 to bitmap - kotlin

I am trying to decode base64 string type image to bitmap but my android studio is not recognizing "decode" method in
val imageBytes = Base64.decode(string, 0)
val image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

This could caused by importing the wrong class. It might be that Android Studio is interpreting that as java.util.Base64 which has no decode method. Instead, you want to use the Base64 class declared in android.util. Try using a fully qualified reference to make sure the IDE selects the right one
val encodedImage: String
val imageBytes = android.util.Base64.decode(encodedImage, 0)

Related

Convert html content to PDF Byte Array with kotlin

val sanitizedHTML = Jsoup.clean(html, whitelist)
val textRenderer = ITextRenderer()
val outputStream = ByteArrayOutputStream()
textRenderer.setDocumentFromString(sanitizedHTML)
textRenderer.layout()
textRenderer.createPDF(outputStream)
textRenderer.finishPDF()
return Base64.getDecoder().decode(outputStream.toByteArray())
I would like to generate pdf from html content and rather than saving as file, would like to upload to server which expects it to be ByteArray.
I tried to do above using jsoup to clean html and textRenderer for generating pdf but keep receiving error about invalid Base64 character 25. Could someone help what I am doing wrong here.
return Base64.getDecoder().decode(outputStream.toByteArray())
This was incorrect, if I remove Base64 decoding it is working well.

Cannot serialize a string object with Microsoft.Bond

I am using Microsoft.Bond to serialize a class object which works perfectly fine. However, when I try to serialize a simple System.String object, the CompactBinaryWriter writes almost nothing to the output buffer. I am using this code:
string v = "test data";
var outputBuffer = new OutputBuffer();
var writer = new CompactBinaryWriter<OutputBuffer>(outputBuffer);
Serialize.To(writer, v);
var output = outputBuffer.Data;
output in this case is a one element array : {0}, irrespective of the value of v. Can someone point out why this doesn't work?
Bond requires a top-level Bond struct to perform serialization/deserialization.
If only one value needs to be passed/returned, the type bond.Box<T> can be used to quickly wrap a value in a Bond struct. (There's nothing special about bond.Box<T>, except that it ships with Bond.)
Try this:
Serialize.To(writer, Bond.Box.Create(v));
You'll need to deserialize into a bond.Box<string>.
There's an open issue about having better behavior in cases like this.

New to akka-http

I am new to akka-http. I am using this in my project. I am not able to understand what exactly marshalling and unmarshalling is.
If someone can explain it with a brief example showing how to marshall and unmarshall json.
When you receive a request the in http it is in wire format i.e byte string, Unmarshaling is converting this byte string to higher level format, on the flip side is marshaling were you convert to low level format.
Example in akka-http of converting json string(str) to case class(person):
case class Person(name: String, age: Int)
val str = """{"name": "some", "aga": 10}"""
impicit val jsonF = jsonFormat2(Person)
val person = JsonParser(str).convertTo[Person]
But a better approach is using the entity directive from akka-http:
val route = post {
entity(as[Person]) { person =>
complete(s"Person: ${person.name} - favorite number: ${person.favoriteNumber}")
}
}
The example from the documentation here
by the way you need the implicit formater in your scope for unmarshaling to succeed and the number to match the number of field in your case class.

Encode and decode Bitmapdata for encryption

Flash CS6 (AS3):
This is what I am trying to accomplish...
Convert bitmapdata -> bytearray -> encode using JPEGencoder (PNGencoder, or any other alternatives) -> base64 string.
Once i get hold of this base64 string, I will be able to use my string obfuscation algorithm, and send that string to php.
Now the reverse (decryption) to get back my original image.
Load the obfuscated string from php into flash -> deobfuscation algorithm -> decodebase64toBytearray -> bitmapdata
The challenge for me rite now is in converting base64 to bytearray, and then to bitmapdata.
Can someone guide me on how to get back the bitmap image from base64 string?
var pBytes:ByteArray = Base64.decodeToByteArray(pString);
var pBitmapData:BitmapData = PNGEncoder2.decode(pBytes);

iTextSharp: Convert PdfObject to PdfStream

I am attempting to pull some font streams out of a pdf file (legality is not an issue, as my company has paid for the rights to display these documents in their original manner - and this requires a conversion which requires the extraction of the fonts).
Now, I had been using MUTool - but it also extracts the images in the pdf as well with no method for bypassing them and some of these contain 10s of thousands of images. So, I took to the web for answers and have come to the following solution:
I get all of the fonts into a font dictionary and then I attempt to convert them into PdfStreams (for flatedecode and then writing to files) using the following code:
PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject((PdfObject)cItem.pObj);
PdfName type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
try
{
int xrefIdx = ((PRIndirectReference)((PdfObject)cItem.pObj)).Number;
PdfObject pdfObj = (PdfObject)reader.GetPdfObject(xrefIdx);
PdfStream str = (PdfStream)(pdfObj);
byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)str);
}
catch { }
But, when I get to PdfStream str = (PdfStream)(pdfObj); I get the error below:
Unable to cast object of type 'iTextSharp.text.pdf.PdfDictionary'
to type 'iTextSharp.text.pdf.PdfStream'.
Now, I know that PdfDictionary derives from (extends) PdfObject so I am uncertain as to what I am doing incorrectly here. Someone please help - I either need advice on patching this code, or if entirely incorrect, either code to extract the stream properly or direction to a place with said code.
Thank you.
EDIT
My revised code is here:
public static void GetStreams(PdfReader pdf)
{
int page_count = pdf.NumberOfPages;
for (int i = 1; i <= page_count; i++)
{
PdfDictionary pg = pdf.GetPageN(i);
PdfDictionary fObj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.FONT));
if (fObj != null)
{
foreach (PdfName name in fObj.Keys)
{
PdfObject obj = fObj.Get(name);
if (obj.IsIndirect())
{
PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
PdfName type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
int xrefIdx = ((PRIndirectReference)obj).Number;
PdfObject pdfObj = pdf.GetPdfObject(xrefIdx);
if (pdfObj == null && pdfObj.IsStream())
{
PdfStream str = (PdfStream)(pdfObj);
byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)str);
}
}
}
}
}
}
However, I am still receiving the same error - so I am assuming that this is an incorrect method of retrieving font streams. The same document has had fonts extracted using muTool successfully - so I know the problem is me and not the pdf.
There are at least two things wrong in your code:
You cast an object to a stream without performing this check: if (pdfObj == null && pdfObj.isStream()) { // cast to stream } As you get the error message that you're trying to cast a dictionary to a stream, I'm 99% sure that the second part of the check will return false whereas pdfObj.isDictionary() probably returns true.
You try extracting a stream from PdfReader and you're trying to cast that object to a PdfStream instead of to a PRStream. PdfStream is the object we use to create PDFs, PRStream is the object used when we inspect PDFs using PdfReader.
You should fix this problem first.
Now for your general question. If you read ISO-32000-1, you'll discover that a font is defined using a font dictionary. If the font is embedded (fully or partly), the font dictionary will refer to a stream. This stream can contain the full font information, but most of the times, you'll only get a subset of the glyphs (because that's best practice when creating a PDF).
Take a look at the example ListFontFiles from my book "iText in Action" to get a first impression of how fonts are organized inside a PDF. You'll need to combine this example with ISO-32000-1 to find more info about the difference between FONTFILE, FONTFILE2 and FONTFILE3.
I've also written an example that replaces an unembedded font with a font file: EmbedFontPostFacto. This example serves as an introduction to explain how difficult font replacement is.
Please go to http://tinyurl.com/iiacsCH16 if you need the C# version of the book samples.