JxBrowser - Save cached image - jxbrowser

Is there a way to save a cached image from a loaded page? I would like to be able to right click on a image and have a option to "Save image as...". I know I could extract the image url and download it but if the image changes I won't be able to get the current one displayed on the page.

Right now JxBrowser API doesn't provide functionality that allows saving images via approach you are requesting.
This feature will be implemented in one of the next JxBrowser versions. I will let you know when updated build with the feature is available for download.

YOu can try this solution:
NetworkService networkService = browser.getContext().getNetworkService();
networkService.setNetworkDelegate(new DefaultNetworkDelegate() {
#Override
public void onDataReceived(DataReceivedParams params) {
if (params.getMimeType().equals("image/png")) {
byte[] img = params.getData();
if(img!=null){
ByteArrayToImage("png",img);
System.out.println("PNG image data = " + Arrays.toString(img));
}
}
if (params.getMimeType().equals("image/jpeg") || params.getMimeType().equals("image/jpg")) {
byte[] img = params.getData();
if(img!=null){
ByteArrayToImage("jpg",img);
System.out.println("jpeg image data = " + Arrays.toString(img));
}
}
}
});
With utility image routine:
public static void ByteArrayToImage(String imageType, byte[] data) {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
BufferedImage bImage2;
Random rn = new Random();
int random = rn.nextInt(100) + 1;
try {
bImage2 = ImageIO.read(bis);
ImageIO.write(bImage2, imageType, new File("D://tmp//output"+random+"." + imageType) );
System.out.println("image created");
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

Related

Is there a way to reduce the file size saved from a byte array in xamarin?

Right now im trying to save an image using DI in Xamarin Forms, but the problem im facing now is that the file im saving is way bigger than the original file that im reading from (im using bitoobitImageEditor to load the file from my device). The original image is 200kb yet the image saved is 773kb. Is there something i can do about this?
this is my file saving function
public void SavePictureToDisk(string filename, byte[] imageData)
{
var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
var pictures = dir.AbsolutePath;
//adding a time stamp time file name to allow saving more than one image... otherwise it overwrites the previous saved image of the same name
string name = filename + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpeg";
string filePath = System.IO.Path.Combine(pictures, name);
try
{
System.IO.File.WriteAllBytes(filePath, imageData);
//mediascan adds the saved image into the gallery
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Android.Net.Uri.FromFile(new File(filePath)));
Xamarin.Forms.Forms.Context.SendBroadcast(mediaScanIntent);
}
catch (System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
and this is my photo reading function
public ICommand GalleryButton_Clicked => new Command(async () =>
{
frontimage = await ImageEditor.Instance.GetEditedImage(null, Config);
if (frontimage != null)
{
PhotoImageFront.Source = ImageSource.FromStream(() => new MemoryStream(frontimage));
}
});

Xamarin.Forms failing to use EvoHtmlToPdfclient in order to convert html string to a pdf file

I'm using Xamarin.Forms and I am trying to convert an html string to a pdf file using EvoPdfConverter, but the problem is that when I try to do so, on the line htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString()); in the code snippet below, the app just freezes and does nothing, seems like it wants to connect to the given IP, but it can't, however I don't get any errors or exceptions! not even catch!! does anybody know what I should do to resolve this issue? and here is my code for this:
public void ConvertHtmlToPfd(string htmlData)
{
ServerSocket s = new ServerSocket(0);
HtmlToPdfConverter htmlToPdfConverter = new
HtmlToPdfConverter(GetLocalIPAddress(),(uint)s.LocalPort);
htmlToPdfConverter.TriggeringMode = TriggeringMode.Auto;
htmlToPdfConverter.PdfDocumentOptions.CompressCrossReference = true;
htmlToPdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Best;
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
}
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.ReadExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
}
try
{
// create the HTML to PDF converter object
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
Java.IO.File myDir = new Java.IO.File(root + "/Reports");
try
{
myDir.Mkdir();
}
catch (Exception e)
{
string message = e.Message;
}
Java.IO.File file = new Java.IO.File(myDir, filename);
if (file.Exists()) file.Delete();
htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString());
}
catch (Exception ex)
{
string message = ex.Message;
}
}
Could you try to set a base URL to ConvertHtmlToFile call as the second parameter? You passed an empty string. That helps to resolve the relative URLs found in HTML to full URLs. The converter might have delays when trying to retrieve content from invalid resources URLs.

Generating PDFs using Phantom JS on .NET applications

I have been looking into phantomJS and looks like it could be a great tool to use generating PDFs. I wonder if anyone have successfully used it for their .NET applications.
My specific question is: how would you use modules like rasterize.js on the server, receive requests and send back generated pdfs as a response.
My general question is: is there any best practice for using phantomJS with .NET Applications. What would be the best way to achieve it?
I am fairly new in .NET World and I would appreciate the more detailed answers. Thanks everyone. :)
I don't know about best practices, but, I'm using phantomJS with no problems with the following code.
public ActionResult DownloadStatement(int id)
{
string serverPath = HttpContext.Server.MapPath("~/Phantomjs/");
string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".pdf";
new Thread(new ParameterizedThreadStart(x =>
{
ExecuteCommand("cd " + serverPath + #" & phantomjs rasterize.js http://localhost:8080/filetopdf/" + id.ToString() + " " + filename + #" ""A4""");
})).Start();
var filePath = Path.Combine(HttpContext.Server.MapPath("~/Phantomjs/"), filename);
var stream = new MemoryStream();
byte[] bytes = DoWhile(filePath);
return File(bytes, "application/pdf", filename);
}
private void ExecuteCommand(string Command)
{
try
{
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;
Process = Process.Start(ProcessInfo);
}
catch { }
}
public ViewResult FileToPDF(int id)
{
var viewModel = file.Get(id);
return View(viewModel);
}
private byte[] DoWhile(string filePath)
{
byte[] bytes = new byte[0];
bool fail = true;
while (fail)
{
try
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
}
fail = false;
}
catch
{
Thread.Sleep(1000);
}
}
System.IO.File.Delete(filePath);
return bytes;
}
Here is the action flow:
The user clicks on a link to DownloadStatement Action. Inside there, a new Thread is created to call the ExecuteCommand method.
The ExecuteCommand method is responsible to call phantomJS. The string passed as an argument do the following.
Go to the location where the phantomJS app is and, after that, call rasterize.js with an URL, the filename to be created and a print format. (More about rasterize here).
In my case, what I really want to print is the content delivered by the action filetoupload. It's a simple action that returns a simple view. PhantomJS will call the URL passed as parameter and do all the magic.
While phantomJS is still creating the file, (I guess) I can not return the request made by the client. And that is why I used the DoWhile method. It will hold the request until the file is created by phantomJS and loaded by the app to the request.
If you're open to using NReco.PhantomJS, which provides a .NET wrapper for PhantomJS, you can do this very succinctly.
public async Task<ActionResult> DownloadPdf() {
var phantomJS = new PhantomJS();
try {
var temp = Path.Combine(Path.GetTempPath(),
Path.ChangeExtension(Path.GetRandomFileName(), "pdf")); //must end in .pdf
try {
await phantomJS.RunAsync(HttpContext.Server.MapPath("~/Scripts/rasterize.js"),
new[] { "https://www.google.com", temp });
return File(System.IO.File.ReadAllBytes(temp), "application/pdf");
}
finally {
System.IO.File.Delete(temp);
}
}
finally {
phantomJS.Abort();
}
}
Here's some very basic code to generate a PDF using Phantom.JS but you can find more information here: https://buttercms.com/blog/generating-pdfs-with-node
var webPage = require('webpage');
var page = webPage.create();
page.viewportSize = { width: 1920, height: 1080 };
page.open("http://www.google.com", function start(status) {
page.render('google_home.pdf, {format: 'pdf', quality: '100'});
phantom.exit();
});

HttpHandler [Image] cannot be displayed because it contains errors

Ok i have been working non stop on this and doing a lot of searching. I cannot get my images to display when pulling them from the database. If i try going to the handler link manually i get a message saying "The image [Image] cannot be displayed because it contains errors". I had some old images in the database from before and it first displayed those correctly. But now if i update images it will give me this error when trying to view them.
Upload code.
if (fileuploadImage.HasFile)
{
if (IsValidImage(fileuploadImage))
{
int length = fileuploadImage.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileuploadImage.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
if (mainImage == null)
{
ProfileImage image = new ProfileImage();
image.ImageName = txtImageName.Text;
image.ImageData = imgbyte;
image.ImageType = img.ContentType;
image.MainImage = true;
image.PersonID = personID;
if (image.CreateImage() <= 0)
{
SetError("There was an error uploading this image.");
}
}
else
{
mainImage.ImageName = txtImageName.Text;
mainImage.ImageType = img.ContentType;
mainImage.ImageData = imgbyte;
mainImage.MainImage = true;
mainImage.PersonID = personID;
if (!mainImage.UpdateImage())
{
SetError("There was an error uploading this image.");
}
}
}
else
{
SetError("Not a valid image type.");
}
Here is my image handler:
public class ImageHandler : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
int imageid = Parser.GetInt(context.Request.QueryString["ImID"]);
ProfileImage image = new ProfileImage(Parser.GetInt(imageid));
context.Response.ContentType = image.ImageType;
context.Response.Clear();
context.Response.BinaryWrite(image.ImageData);
context.Response.End();
}
And this is how i'm calling it "~/ImageHandler.ashx?ImID=" + Parser.GetString(image.ImageID)
I'm using the data type Image in sql server to store this.
Edit:
I also found out that if i put a try catch around context.Response.end() it is erroring out saying the "Unable to evaluate the code because the native frame..."
I found my problem. I was checking the header of the actual file to make sure it was valid. Somehow that was altering the data and making it bad.

Sometimes Image is not displaying for only one user

I am having ASP.NET MVC application in which i am using HTTP handler ashx file to get the image on the page . This image is uploaded by user by scanning the document.
Now my problem is for every user its displaying except one , User is reporting he is not able to see the image even though it was loaded sucessfully , when i checked the logs it shown that server got image.
No exception was logged at the server while converting image too :(
One more thing this is happening frequently , 70% times user is not able to see the image in the page. 30% time he managed to see the image ...
Strange issue
Please advice what could be the issue ?
Below is my code
public class GetImage : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public GetImage()
{
}
public void ProcessRequest(HttpContext context)
{
if (context != null)
{
if (!string.IsNullOrEmpty(context.Request.Params["side"]))
{
bool isFront = false;
if (context.Request.Params["side"].Equals("Front"))
{
isFront = true;
}
else
{
isFront = false;
}
ICache Cache = CacheManager.SessionCache;
DepositState depState = (DepositState)Cache[Constants.DepositSession];
if (depState != null)
{
byte[] imageByteArray = null;
System.IO.MemoryStream imageMemoryStream = null;
try
{
if (isFront)
{
imageByteArray = System.Convert.FromBase64String(depState.FrontJpegBase64);
}
else
{
imageByteArray = System.Convert.FromBase64String(depState.BackJpegBase64);
}
imageMemoryStream = new System.IO.MemoryStream(imageByteArray);
using (System.Drawing.Image img = System.Drawing.Image.FromStream(imageMemoryStream))
{
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
catch(Exception ex)
{
Log.Error(Constants.DefaultErrorCode, "Exception occured while converting image to Base 64 in GetImage.ashx.cs" + ex);
}
imageMemoryStream.Close();
context.Response.Flush();
}
else
{
Log.Error(Constants.DefaultErrorCode, " Deposit State object is nullin GetImage.ashx ");
}
}
}
else
{
Log.Error(Constants.DefaultErrorCode, "Context is null in the Process Request ");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
I don't see where you are setting the context.Response.ContentType. I haven't tested this, but I wonder if the missing header would cause unpredictable browser behavior.

Resources