Image conversion and view in Chrome browser - google-chrome

I have a bytearray of a tiff image. When I convert into the same format, image opens. But when I convert it into jpg, it doesn't (in Chrome, but works in IE).
PS: I want to directly convert the bytearray to show image dynamically as per my requirement.
ByteArrayOutputStream bOutStream = new ByteArrayOutputStream();
bOutStream = < ... Tiff image Stream Received from my API Call... >
byte[] chqImage = bOutStream.toByteArray();
response.setContentType("image/jpeg");
BufferedOutputStream output = null;
output = new BufferedOutputStream(response.getOutputStream());
output.write( bOutStream.toByteArray());
output.flush();

You're going to need to actually translate the image itself from TIFF to JPEG. To do that, I recommend reviewing the ImageIO library in Java.
I feel like the javadoc for that library is pretty straightforward, so you should be OK there.

Related

base64 embeded PDF files won't render in Chrome

Some PDF files won't render in Chrome browser but will render fine in Firefox. All files render fine in all browsers if emeded directly.
<object id="content-view" :data="content_view.base64" type="application/pdf"></object>
The confusing part is that the problem is only for some files and not all. Files are stored in a folder that is not public and that's why they are served as base64 for the user to view.
I tested the problematic files by using online base64 decoders and I get the same result. Rendered in FF, not rendered in Chrome.
I cannot share any of the PDF files. They are all from the same source, scanned from the same device, PDF version 1.4, 4 pages.
I have tried:
using iframe, embed and object (same result)
unblocking Insecure content in Chrome site settings
opening and re-saving in Adobe Acrobat
using online PDF analyzers to see if any problems present (none found)
I had the exact same issue. I noticed that some of the PDFs that are more than 1MB isn't loading.
I found a solution here: Open base64 encoded pdf file using javascript. Issue with file size larger than 2 MB
Need to change the Base64 string to a BLOB. Then create a URL to be used for iframe src.
Here is the code:
base64PDFToBlobUrl( base64 ) {
const binStr = atob( base64 );
const len = binStr.length;
const arr = new Uint8Array(len);
for (let i = 0; i < len; i++) {
arr[ i ] = binStr.charCodeAt( i );
}
const blob = new Blob( [ arr ], { type: 'application/pdf' } );
const url = URL.createObjectURL( blob );
return url;
}
This will return a url that you can put inside your iframe, embed or object src. This way, you can still load the PDF in a page without opening it in another tab.
Rather than use the browsers native PDF renderer, you could use the JS one written by Mozilla.
ViewerJS provides a nice interface to this and if you want to embed it fullsize in a page, then you can place it in an iframe and control that with iFrame-resizer.
Instead of opening the PDF file in HTML object element, open it in a new window using Blob URL.
Please refer
Creating a BLOB from a Base64 string in JavaScript
to convert Base64 to Blob

Find file format of loaded bitmap with SkiaSharp?

I'm trying to figure out the format of an image that is loaded by an array of bytes into an SKBitmap. I'd just like to know if it is a JPEG or PNG, etc.
// Was the decoding done by a JPEG decoder or PNG or?
var bitmap = SKBitmap.Decode(buffer);
Is this possible?
I would have a look at SKCodec.
https://learn.microsoft.com/dotnet/api/skiasharp.skcodec
That doesn't even load the actual image data out the box - just the headers. The way, you don't use stacks of memory when reading the file type.
To read the type, use the EncodedFormat property:
https://learn.microsoft.com/dotnet/api/skiasharp.skcodec.encodedformat
using var codec = SKCodec.Create(...);
var format = codec.EncodedFormat;

Send opencv Mat image through Qt websocket to HTML client

I'm trying to write an application in c++ using Qt 5.7, basically it should be a websocket server, using qwebsocket for this, capable to send an image elaborated with opencv to an HTML client. What I'm trying to do is encode the image in base64, transmit and on the client put the encoded string in the src of an image tag.
Just to test, I can send/receive text messages correctly, so the websocket architecture is working, but I have some problems with images. This is my code snippets:
Server
cv::Mat imgIn;
imgIn = cv::imread("/home/me/color.png",CV_LOAD_IMAGE_COLOR);
QByteArray Img((char*)(imgIn.data),imgIn.total()*imgIn.elemSize());
QByteArray Img64 = Img.toBase64();
pClient->sendBinaryMessage(Img64);
Client
<img id="ItemPreview" src="" style="border:5px solid black" />
....
websocket.binaryType = "arraybuffer";
websocket.onmessage = function (evt) {
console.log( "Message received :", evt.data );
document.getElementById("ItemPreview").src = "data:image/png;base64," + evt.data;
};
I think most of the problems are in the Server, because the base64 sequence I got from the image is different from the one I can get from online converter image/base64.
On the client I receive this error in the console and nothing is showed:
data:image/png;base64,[object ArrayBuffer]:1 GET
data:image/png;base64,[object ArrayBuffer] net::ERR_INVALID_URL
Any hints?
SOLUTION
Thanks to the suggestions, I can provide the working code:
Server
imgIn = cv::imread("/home/me/color.png", CV_LOAD_IMAGE_UNCHANGED);
std::vector<uchar> buffer;
cv::imencode(".png",imgIn,buffer);
std::string s = base64_encode(buffer.data(),buffer.size());
pClient->sendTextMessage(QString::fromStdString(s));
Client
Removed this line:
websocket.binaryType = "arraybuffer";
The base64 encoding in the server is done using this code:
Encode/Decode base64
This line in the server:
imgIn = cv::imread("/home/me/color.png",CV_LOAD_IMAGE_COLOR);
decodes a PNG formatted image, and places it in memory as load of pixel data (plus possibly some row padding, which you don't take account of, see below). That's what you're base64 encoding.
This line in the client:
document.getElementById("ItemPreview").src = "data:image/png;base64," + evt.data;
is expecting a PNG image, but that isn't what you're sending; you've just pushed out a load of raw pixel data, with no dimensions or stride or format information or anything else.
If your client wants a PNG, you're going to have to use something like imencode to write PNG data to a memory buffer, and base64 encode that instead.
One other important thing to note is that decoded images may have row padding... a few bytes on the end of each row for memory alignment purposes. Therefore, the actual length of each image row may exceed the width of the image multiplied by the size of the each pixel in bytes. That means that this operation:
QByteArray Img((char*)(imgIn.data),imgIn.total()*imgIn.elemSize());
may not, in fact, wrap the entire image buffer in your QByteArray. There are various ways to check the stride/step of an image, but you'd best read the cv::Mat docs as it isn't worth me repeating them all here. This only matters if you're doing raw byte-level image manipulation, like you are here. If you use imencode, you don't need to worry about this.

saving webcam image to a website

How can i save a webcam screenshot to a website?
I know you can save it to your hard drive using:
var browseFileReference = new FileReference();
browseFileReference.save(video);
But how would i go about it to save this image to a website, lets say flickr or facebook or something.
Any help?
You should have a look at existing AS3 library.
Flickr : http://code.google.com/p/as3flickrlib/
Facebook : http://www.adobe.com/devnet/facebook.html
The basic steps are, generate the bitmap data for the region you want, use one of the F/OSS libraries to generate PNG or JPEG data, base64 the data, and then generate a URLRequest with the encoded image as POST data, which can hen be handled server side. I would have to dig through projects to find the proper classes I have to do this to show a real example, but this is actually really simple. Each of the steps I outline can be implemented in a few lines of code using existing libraries.
You can save the screenshot of the webcam as ByteArray. Make sure you have the JPGEncoder class (from the as3corelib).
// bitmapdata
var btmData:BitmapData = new BitmapData(video.width, video.height);
btmData.draw(video);
// make jpg
var jpgEncoder:JPGEncoder = new JPGEncoder(90);
var jpgBytes:ByteArray = jpgEncoder.encode(btmData);
Now, you can use the as3flickrlib to connect with Flickr. Danny Patterson wrote a nice article to upload a ByteArray to Flickr with this library, see http://blog.dannypatterson.net/2009/08/upload-bytearray-to-flickr/
Edit: I would first try to upload it to Facebook, that is much easier than uploading an image to Flickr.

HTML inside webView

I am posting some data to a server using DefaultHttpClient class and in the response stream I am getting a HTML file. I save the stream as a string and pass it onto another activity which contains a WebView to render this HTML on the screen:
response = httpClient.execute(get);
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuffer sb = new StringBuffer();
String line;
while((line=br.readLine())!=null){
sb.append(line);
sb.append("\n");
}
is.close();
Intent intent = new Intent(this,Trial.class);
intent.putExtra("trial",sb.toString());
startActivity(intent);
Log.i("SB",sb.toString());
In Second Activity, the code to load the WebView reads:
WebView browser = ((WebView)findViewById(R.id.trial_web));
browser.getSettings().setJavaScriptEnabled(true);
browser.loadData(html,"text/html", "utf-8");
When I run this code, the WebView is not able to render the HTML content properly. It actually shows the HTML string in URL encoded format on the screen. Interestingly, If I copy the Loggers output to HTML file and then load this HTML in my WebView(using webview.loadurl(file:///assets/xyz.html)) everything works fine.
I suspect some problem with character encoding.
What is going wrong here? Please help.
Thanks.
Try using a BasicResponseHandler rather than converting it all into a string yourself. See here for an example. I am skeptical this will help, but it will simplify your code and let you get rid of the inefficient StringBuffer.
Also, you might try switching to loadDataWithBaseURL(), as I have had poor results with loadData(). The aforementioned example shows this as well.