Image file stored in original input format in place of mentioned format - javax.imageio

Hi I am taking input image in any format from browser and passing it to server.At server site added saveImage() method for storing image in .jpeg format but it stored same as original format which accepted in browser.
Here is my code
public boolean saveImage(byte[] byteImage, String transactionId) {
InputStream in = new ByteArrayInputStream(byteImage);
try {
BufferedImage bImageFromConvert = ImageIO.read(in);
File imageFile = new File(filePath+ transactionId + ".jpeg");
ImageIO.write(bImageFromConvert, "jpg", imageFile);
return true;
} catch (IOException e) {
System.out.println("error===" + e.getMessage());
return false;
}
}

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.

JxBrowser - Save cached image

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);
}
}

Vaadin 7: File Upload

I have a Upload component in which I´m supposed to import a xml file in order to parse it.
I´m trying to use the File.createTempFile method to create the file phisically,but something weird is going on.
For example,if I take the file named "test.xml" and use the createTempFile method to create it on the disk,the name of the generate file becomes something like 'test.xml13234xml'.How can I create the file the correct way?
This is expected when using i.e. createTempFile method as it implicitly creates a file with random prefix:
// a part of createTempFile method
private static final SecureRandom random = new SecureRandom();
static File generateFile(String prefix, String suffix, File dir) {
long n = random.nextLong();
if (n == Long.MIN_VALUE) {
n = 0; // corner case
} else {
n = Math.abs(n);
}
return new File(dir, prefix + Long.toString(n) + suffix);
}
which should give something like 'test.xml13234xml'.
If you want to create a file with the correct name and keep it for later use you can rename/move it within uploadSucceeded method.
public class ExampleUpload implements Upload.Receiver, Upload.SucceededListener {
private Upload xmlUpload;
private File tempFile;
public ExampleUpload() {
this.xmlUpload = new Upload("Upload:", this);
this.xmlUpload.addSucceededListener(this);
}
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
try {
tempFile = File.createTempFile(filename, "xml");
tempFile.deleteOnExit();
return new FileOutputStream(tempFile);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void uploadSucceeded(SucceededEvent event) {
try {
File destinationFile = new File("c:\\" + event.getFilename());
FileUtils.moveFile(tempFile, destinationFile));
// TODO read and parse destinationFile
} catch (IOException e) {
e.printStackTrace();
}
}
}

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.

Resources