I have used below code to fetch image from server. I have 60 different images placed on server. I have urls of all those images. By using while loop I am getting all these images but it's taking so much time to load image from server.
What can I do to get these images as fast as possible?
public Image getImagefromURL(String imageURL) {
DataInputStream is = null;
StringBuffer sb = new StringBuffer();
Image img = null;
try {
HttpConnection c = (HttpConnection) Connector.open(imageURL);
int len = (int) c.getLength();
if (len > 0) {
is = c.openDataInputStream();
byte[] data = new byte[len];
is.readFully(data);
img = Image.createImage(data, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
return img;
}
And also one thing is happening that when I fetch first image, application is confirming me like "Application wants to connect to [URL of image location] using airtime. IS it ok to use airtime?" here I want to hide my path of image location. How can I do that?
The bigger the image, the longer it will take to load it. Make sure your PNG images are compressed with a tool, for example, PNGGauntlet.
You can also add a local cache on the application side using RMS.
And a last tip... You should not rely on HttpConnection.getLength, it might come as zero even when there is data to be read.
Related
Good day ,I am generating certificates and for this I have a template where I must write user data, for the moment I am creating the certificates in pdf format, but the ideal would be to use images or convert those pdf to image since it is easier for the user to handle images, I have not found any library capable of writing in images that works correctly.
At the moment I am trying to use Image. https://pub.dev/packages/image.
I have the following code, but it fails to add a text fragment in the image.
imagecert = await ManagerDB().getcertificate(certificatetemplate); //imagecert is uint8list
if (imagecert != null) {
mg.Image ima = mg.Image.fromBytes(300, 200, List.from(imagecert)); Image works with list<int>
mg.Image imag = mg.drawString(ima, mg.arial_14, 0, 0, 'Hello World'); //here the code does not work
List<int> data = mg.encodePng(imag);
Uint8List bytes = Uint8List.fromList(data);
setState(() {});
return bytes;
} else {
print("Enlace no encontrado");
}
I don't know if there is a simpler solution to write text in an image. It is required to store those images.
Thank you
you can put image inside widget and add to that widget text
and converted to image using globalKey (don't forget to pass globalKey to key of that sepecific widget )
Future<Uint8List> _convertWidgetToImage(GlobalKey globalKey) async {
RenderRepaintBoundary boundary =
globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
ui.Image image = await boundary.toImage();
ByteData byteData =
(await (image.toByteData(format: ui.ImageByteFormat.png)))!;
Uint8List pngBytes = byteData.buffer.asUint8List();
return pngBytes;
}
I'm trying to save the content of a MovieClip in a JPEG image, but when I save it the image has this problem:
There is a blank space in it (obvious from quote formatting), this appears in all the images that I try to save using filereference with JPGEncoder.
I believe that the problem might be happening because of the JPGEncoder class but I'm not sure about it.
This is the function I'm using to save the image (some of the strings are in portuguese):
private function fl_Salvar(event:MouseEvent)
{
try
{
var src:BitmapData = new BitmapData(imageViewer.width,imageViewer.height);
var mtx:Matrix = DisplayUtils.fitIntoRect(imageViewer.mcImage.getChildAt(0),rect,true,Alignment.MIDDLE,false);
src.draw(imageViewer,mtx,null,null,null,true);
var jpgEncoder:JPGEncoder = new JPGEncoder(85);
var imgStream:ByteArray = null;
imgStream = jpgEncoder.encode(src);
var file:FileReference = new FileReference();
file.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
file.save( imgStream, "TESTE.jpg");
}
catch (ioe:IllegalOperationError)
{
trace("Operação Ilegal.");
}
catch (ae:ArgumentError)
{
trace("Argumento Inválido.");
}
catch (me:MemoryError)
{
trace("Memória Insuficiente.");
}
catch (error:Error)
{
trace("Erro ao tentar salvar imagem : "
+ " . Erro : " + error);
}
}
private function ioErrorHandler( event:IOErrorEvent ):void
{
trace("Handler de erro I/O: " + event);
}
I would like to know if someone knows what might be causing this.
Thanks in advance.
Edit:
Here is my rect declaration:
rect = new Rectangle(imageViewer.mcImage.x,imageViewer.mcImage.y,imageViewer.mcImage.width,imageViewer.mcImage.height);
It's because of these two lines:
var mtx:Matrix = DisplayUtils.fitIntoRect(imageViewer.mcImage.getChildAt(0),rect,true,Alignment.MIDDLE,false);
src.draw(imageViewer,mtx,null,null,null,true);
What they do is that they fit your image inside some rect. You haven't provided info what's that rect and how it's defined, but I guess it has some dimensions. So you are fitting image in, and it's not stretched, but resized on the longer side.
Encoder works well, you just need to check the rectangle that you want to fit the image in.
Are you sure it is not you picture viewing software that is doing this? The image seems complete (they are written out to a byteArray pixel by pixel from top left to lower right.) if it were the file stream or byte array that were the trouble I would expect to see a distorted picture.
Is there actually a part of the image missing, or is that the full image?
I'm receiving an image on a Metro app through network socket every 1 second, loading it in an array of bytes, then convert it to a BitmapImage and display it later. All of this work fine.
The image is changing constantly on the other side. For some reason, it throws an OutOfMemory exceptions from now and then(like 1 in 10) . I fixed it by clearing the array of bytes every time the image is received. Now it works like charm.
See below for my main issue:
public static BitmapImage imag;
public static byte[] save = new byte[1];
if(recieved)
{
await reader.LoadAsync(4);
var sz = reader.ReadUInt32(); //read size
await reader.LoadAsync(sz); //read content
save = new byte[sz];
reader.ReadBytes(save);
await ImgSrcFromBytes(save)
Array.Clear(save, 0, save.Length); //issue here !!
}
public async Task<ImageSource> ImgSrcFromBytes(byte[] a)
{
imag = new BitmapImage();
var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
await stream.WriteAsync(a.AsBuffer());
stream.Seek(0);
imag.SetSource(stream);
return imag;
}
Now, i'm implementing a new function to save the image as a file if requested by the user with the code below, however, if i clear the array of bytes above, i get an unreadable image, but if i don't clear the array, i get a perfect image.
Note that no exceptions are thrown and both images have the same size.
FileSavePicker picker = new FileSavePicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.SuggestedFileName = "capture.png";
picker.FileTypeChoices.Add("Png File", new List<string>() { ".png" });
StorageFile file = await picker.PickSaveFileAsync();
if (file != null)
{
CachedFileManager.DeferUpdates(file);
await FileIO.WriteBytesAsync(file, save);
await CachedFileManager.CompleteUpdatesAsync(file);
await new Windows.UI.Popups.MessageDialog("Image Saved Successfully !").ShowAsync();
}
I hope i'm clear. It's a trade-off, if i clear the array, i will get no exceptions while receiving streams over sockets, but i won't be able to get a readable image when saving. and vice versa.
I'm new to working with PdfBox and I'm having a small issue when displaying images. I'm able to import the image, which is sized at 800*900 pixels, and looks fine when viewed in an existing pdf at 100%. However when the resulting PDF is generated using the below code, the image becomes blurry, and the image extends beyond the boundaries of the A4 page.
Is there a different way of sizing/saving images so that they display correctly in pdfbox?
public class PDFtest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException, COSVisitorException {
// TODO code application logic here
// Create a document and add a page to it
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
// Create a new font object selecting one of the PDF base fonts
PDFont font = PDType1Font.HELVETICA_BOLD;
InputStream in = new FileInputStream(new File("img.jpg"));
PDJpeg img = new PDJpeg(document, in);
// Start a new content stream which will "hold" the to be created content
PDPageContentStream contentStream = new PDPageContentStream(document, page);
// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
contentStream.drawImage(img, 10, 700);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.moveTextPositionByAmount(10, 650);
contentStream.drawString("Hello World");
contentStream.endText();
// Make sure that the content stream is closed:
contentStream.close();
// Save the results and ensure that the document is properly closed:
document.save("Hello World.pdf");
document.close();
}
I'd like to point out that as of 2.0 the contentStream.drawXObject function call in Victor's answer is deprecated. If you want to specify a width and height you should use contentStream.drawImage(image, x, y, width, height)
I had the same problem asked in this question, but the given answer is not right.
After some research I found a solution.
Instead of using the function drawImage use the function drawXObject
contentStream.drawXObject( img, 10, 700, 100, 100 );
Where the last two numbers specify the size of the image to be drawn.
For similar situation, for me, with PDF 2.0.11 and a tiff file of dimensions - 1600 x 2100 the following code perfectly fit the image in A4 (portrait) size. Not sure if PDFRectangle is okay with you.
I got this example straight from PDFBOX - Example
The only thing I tweaked/introduced is:
PDRectangle.A4.getWidth(), PDRectangle.A4.getHeight()
Here is the full sample:
public static void main(String[] args) throws IOException
{
// if (args.length != 2)
// {
// System.err.println("usage: " + ImageToPDF.class.getName() + " <image> <output-file>");
// System.exit(1);
// }
String imagePath = "C:/FAX/sample.tiff";
String pdfPath = "C:/FAX/sample.pdf";
if (!pdfPath.endsWith(".pdf"))
{
System.err.println("Last argument must be the destination .pdf file");
System.exit(1);
}
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
// createFromFile is the easiest way with an image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
// draw the image at full size at (x=20, y=20)
try (PDPageContentStream contents = new PDPageContentStream(doc, page))
{
// draw the image at full size at (x=20, y=20)
contents.drawImage(pdImage, 0, 0, PDRectangle.A4.getWidth(), PDRectangle.A4.getHeight());
// to draw the image at half size at (x=20, y=20) use
// contents.drawImage(pdImage, 20, 20, pdImage.getWidth() / 2, pdImage.getHeight() / 2);
}
doc.save(pdfPath);
System.out.println("Tiff converted to PDF succussfully..!");
}
}
Hope it helps.
If your intention is an A4 sized pic on a PDF, then i guess you find the actual size of typical A4 in pixels.
Also you should be aware of the extension of the picture that you want to view like jpg, gif, or bmp ...
from what I saw in your code, the dimensions of the picture are 10 X 700 which I believe is pretty small size.
contentStream.drawImage(img, 10, 700);
And the extension of the picture is : jpg
InputStream in = new FileInputStream(new File("img.jpg"));
check those and return for more info.
that's all.
good luck'''
As per the new API 2.0.x, one can use the PDRectangle to fetch Pdf page width and height. One can use PDPageContentStream to draw the image in accordance with PDF page.
For reference:
try (PDPageContentStream contents = new PDPageContentStream(pdDocument, pdPage)) {
final PDRectangle mediaBox = pdPage.getMediaBox();
final PDImageXObject pdImage = PDImageXObject.createFromFile(image, pdDocument);
contents.drawImage(pdImage, 0, 0, mediaBox.getWidth(), mediaBox.getHeight());
}
I'm trying to ascertain wither there is a limitation on the camera access in the j2me implementation on the HTC Touch2. The native camera is 3MP however it seams that the quality is notably reduced when accessed via j2me, in fact it seams that the only size and format the .getSnapshot() method is able to return is a 240x320 pixel jpeg. I'm trying to confirm that this is a limitation if the j2me implementation and not my coding. Hears and example of some of the things I have tried:
private void showCamera() {
try {
mPlayer = Manager.createPlayer("capture://video");
// mPlayer = Manager.createPlayer("capture://video&encoding=rgb565&width=640&height=480");
mPlayer.realize();
mVideoControl = (VideoControl)mPlayer.getControl("VideoControl");
canvas = new CameraCanvas(this, mVideoControl);
canvas.addCommand(mBackCommand);
canvas.addCommand(mCaptureCommand);
canvas.setCommandListener(this);
mDisplay.setCurrent(canvas);
mPlayer.start();
}
catch (Exception ex) {}
}
public void capture() {
try {
// Get the image.
byte[] raw = mVideoControl.getSnapshot("encoding=jpeg&quality=100&width=640&height=480");
// byte[] raw = mVideoControl.getSnapshot("encoding=png&quality=100&width=
// 640&height=480");
// byte[] raw = mVideoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
// Image thumb = createThumbnail(image);
// Place it in the main form.
if (mMainForm.size() > 0 && mMainForm.get(0) instanceof StringItem)
mMainForm.delete(0);
mMainForm.append(image);
If anyone could help it would be much appreciated.
I have reseved word from a number of sources that there is indeed a limitation on the camera access the JVM has witch is put in place by the operating system.