How I can specify the absolute position of the image? [duplicate] - java

I need to paste 3 pictures in single slide using Apache POI XSLF. However I could able to add only one picture in a slide. Also I could not find any ways to specify the size and orientation the picture should be.
Tried the following code
XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide slide = ppt.createSlide();
XSLFGroupShape group1 = slide.createGroup();
byte buf[] = new byte[1024];
for (int i = 1; i <= 2; i++) {
byte[] pictureData = IOUtils.toByteArray(new FileInputStream(
"C:\\Users\\Ashok\\Pictures\\" + i + ".png"));
int elementIndex = ppt.addPicture(pictureData,
XSLFPictureData.PICTURE_TYPE_PNG);
XSLFPictureShape picture = slide.createPicture(elementIndex);
List<XSLFPictureData> allPictures = ppt.getAllPictures();
System.out.println(allPictures.size());
}
FileOutputStream fos = new FileOutputStream("C:\\test2.pptx");
ppt.write(fos);
fos.flush();
fos.close();
The above code contains only the last image.

You nead to set Anchor to your pictures
for (int i = 1; i <= 2; i++) {
byte[] pictureData = IOUtils.toByteArray(new FileInputStream(
"C:\\Users\\Ashok\\Pictures\\" + i + ".png"));
int elementIndex = ppt.addPicture(pictureData,
XSLFPictureData.PICTURE_TYPE_PNG);
XSLFPictureShape picture = slide.createPicture(elementIndex);
// Set picture position and size
picture.setAnchor(new Rectangle(positionX, positionY, width, height));
List<XSLFPictureData> allPictures = ppt.getAllPictures();
System.out.println(allPictures.size());
}

Related

How to add several barcode images to one image png? [duplicate]

This question already has answers here:
How to combine multiple PNGs into one big PNG file?
(10 answers)
Closed 2 years ago.
My case is what I need to add several barcodes (png) which I generated using Barcode4j library in one png file. I couldn't find any examples, also couldn't make up my mind to solve it. So any help will be appreciated.
Well, I generate barcodes in usual way (throug for) and collecte them in a list of bufferedImages (List). Now I need to glue this images in one.
My code:
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BitmapCanvasProvider canvas = new BitmapCanvasProvider(baos, "image/x-png", 300, BufferedImage.TYPE_BYTE_BINARY, false, 0);
List<BufferedImage> bufferedImageList = new ArrayList<>(); // list for bufferedImages
for (int i = 0; i < barcodesList.size(); i++) {
try {
Code128Bean code128 = new Code128Bean();
code128.setHeight(15f);
code128.setModuleWidth(0.3);
code128.setQuietZone(10);
code128.doQuietZone(true);
code128.generateBarcode(canvas, (String) barcodesList.get(i));
bufferedImageList.add(canvas.getBufferedImage()); // collect images of barcode in cicle
canvas.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
FileOutputStream fos = new FileOutputStream(barcodePath.toString());
// to do smth to make one png from collected images
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Well, my code which combine several barcodes looks like this
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BitmapCanvasProvider canvas = new BitmapCanvasProvider(baos, "image/x-png", 300, BufferedImage.TYPE_BYTE_BINARY, false, 0);
List<BufferedImage> bufferedImageList = new ArrayList<>(); // list for bufferedImages
int sumHeight = 0;
int sumWhide = 0;
int columns = 2;
int rows = 0;
for (int i = 0; i < barcodesList.size(); i++) {
try {
Code128Bean code128 = new Code128Bean();
code128.setHeight(15f);
code128.setModuleWidth(0.3);
code128.setQuietZone(10);
code128.doQuietZone(true);
code128.generateBarcode(canvas, (String) barcodesList.get(i));
sumHeight = sumHeight + canvas.getBufferedImage().getHeight();
sumWhide = sumWhide + canvas.getBufferedImage().getWidth();
bufferedImageList.add(canvas.getBufferedImage()); // collect images of barcode in cycle
canvas.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
double dbl = barcodesList.size() / (double) columns;
rows = (int)Math.ceil(dbl);
int oneWhide = sumWhide / barcodesList.size();
int imgWhide = oneWhide * columns;
int oneHeight = sumHeight / barcodesList.size();
int imgHeight = oneHeight * rows;
BufferedImage bigImage = new BufferedImage(imgWhide, imgHeight, BufferedImage.TYPE_BYTE_BINARY);
Graphics g = bigImage.getGraphics();
int x = 0;
int y = 0;
for (BufferedImage bufferedImage : bufferedImageList) {
g.drawImage(bufferedImage, x, y, null);
x += oneWhide;
if(x >= bigImage.getWidth()){
x = 0;
y += bufferedImage.getHeight();
}
}
ImageIO.write(bigImage,"png",new File(barcodePath.toString()));
} catch (Exception e) {
e.printStackTrace();
}
}

Image transfering btween JavaFX and Android via Bluetooth

I'm trying implement a simple file transfering app.
My app does like that:
1. Capture current camera preview in Android
2. Send it to Javafx application via Bluetooth
3. When Javafx app received the image saving it and show on the window
4. After some drawing over the image capture it then send it to Android again
I implemented like this on Android side first
I created a kind of packet which contains file size, actual data and eof.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
data.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// filesize + data + end of file
String fileSize = String.valueOf(baos.size());
fileSize += '\0'; // end of the filesize string
String eof = "eof"; // end of packet
// set packet size
int packetSize = fileSize.length() + baos.size() + eof.length();
ByteBuffer byteBuffer = ByteBuffer.allocate(packetSize);
byteBuffer.put(fileSize.getBytes());
byteBuffer.put(baos.toByteArray());
byteBuffer.put(eof.getBytes());
byte[] data = new byte[byteBuffer.capacity()];
byteBuffer.position(0);
byteBuffer.get(data);
and send the data to bluetooth outputstream socket
On JavaFX side,
bytes = btIn.read(buffer);
// receive packet data
if (fileSize == null) {
for (int i = 0; i < bytes; i++) {
if (buffer[i] == '\0') {
fileSize = new String(buffer, 0, i);
break;
}
}
}
// eof offset
int offset = bytes - 3;
byte[] eofByte = new byte[3];
eofByte = Arrays.copyOfRange(buffer, offset, bytes);
String message = new String(eofByte, 0, 3);
if (message.equals("eof")) {
eof = true;
fos.write(buffer, 0, bytes-3);
} else {
// set buffer size to file size
if (fileBuffer == null) {
fileBuffer = ByteBuffer.allocate(Integer.parseInt(fileSize));
fileBuffer.put(buffer, fileSize.length()+1, bytes);
fos.write(buffer, fileSize.length()+1, bytes);
} else {
fileBuffer.put(buffer, 0, bytes);
fos.write(buffer, 0, bytes);
// for progress bar
percent = (float) fileBuffer.position() / (float) fileBuffer.capacity();
}
}
log(String.valueOf(percent));
if (eof) {
byte[] data = new byte[fileBuffer.capacity()];
fileBuffer.position(0);
fileBuffer.get(data);
ByteArrayInputStream input = new ByteArrayInputStream(data);
bufferedImage = ImageIO.read(input);
image = SwingFXUtils.toFXImage(bufferedImage, null);
if (bufferedImage != null) {
log("got the image");
}
// set null fileBuffer and fileSize for next images
fileSize = null;
fileBuffer = null;
}
}
above code is for receving image from the Anroid
and Sending part on JavaFX is:
WritableImage writableImage = new WritableImage((int)canvas.getWidth(), (int)canvas.getHeight());
canvas.snapshot(null, writableImage);
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(writableImage, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(bufferedImage, "jpg", baos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] imageInBytes = baos.toByteArray();
log(String.valueOf(imageInBytes.length));
bct.write(imageInBytes);
String eof = "end of file";
byte[] eofbyte = eof.getBytes();
bct.write(eofbyte);
the sending and receiving part work fine..
But I have problems on result images
This is JavaFX side when received the image from Android and ss you see, the most left side of the image is not desired
and more weired after receving image from JavaFX side the result image on Android like this:
My question is how should I fix the code to get correct images?
I think you were hit by this bug:
https://bugs.openjdk.java.net/browse/JDK-8041459
You can avoid this problem by using PNG instead of JPG. Another option is to explicitly convert the image into an image without alpha component before storing it.
Michael

PdfBox-Android adding page text overlay

Stuck with PDFBox-Android, pdfbox-android:1.8.9.0
I load first page of a pdf file, write text in and import this page to a new page of a final document.
Problem is when create new pages, it use last page which contain previous text...
So, first page is ok, but nexts have texts superposed..
private File writeReport() {
File fileSource = new File(getActivity().getApplicationContext().getExternalCacheDir(), "fileSource.pdf");
// get file model in assets
InputStream inputAsset = null;
try {
inputAsset = getActivity().getApplicationContext().getResources().getAssets().open("file_model.pdf");
} catch (IOException e) {
e.printStackTrace();
}
// copy file model in fileSource
try {
OutputStream outputStream = new FileOutputStream(file);
byte buffer[] = new byte[1024];
int length = 0;
while ((length = inputAsset.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputAsset.close();
} catch (IOException e) {
System.out.print("Copy assets : IOException" + e.getMessage());
}
File fileTarget = new File(getActivity().getApplicationContext().getCacheDir(), "fileTarget.pdf");
try {
PDFBoxResourceLoader.init(getActivity().getApplicationContext()); // init lib
PDDocument documentSource = PDDocument.load(fileSource);
PDDocument documentTarget = new PDDocument();
// iteration == a new page
for(int i=0 ; i < 3 ; i++)
{
PDPage page = documentSource.getDocumentCatalog().getPages().get(0);
PDPageContentStream contentStream = new PDPageContentStream(documentSource, page, true, true);
PDFont font1 = PDType1Font.HELVETICA;
float startY = page.getMediaBox().getUpperRightY();
float factor = 2.83f;
page.getStream();
// add text
contentStream.beginText();
contentStream.setFont(font1, 10);
contentStream.newLineAtOffset(factor * 60, startY - (factor * 53));
contentStream.showText("test text" + i);
contentStream.endText();
contentStream.close();
// import source page to output file-> Problem here ! new page contain old overlay text...
documentTarget.importPage(page);
}
documentTarget.save(fileTarget);
documentTarget.close();
documentSource.close();
} catch (IOException e) {
e.printStackTrace();
}
return fileTarget;
}
Is there a way to have fresh page at every iteration ?
Thanks !
The problem is that you reused the same PDPage object, which resulted in the effect that it contained the text of the previous iteration. Solution: use the result of
documentTarget.importPage(page)
and work with that one. Because that is a new PDPage object with everything cloned. So your new code will be like this:
// iteration == a new page
for(int i=0 ; i < 3 ; i++)
{
PDPage page = documentSource.getDocumentCatalog().getPages().get(0);
page = documentTarget.importPage(page); // this is now a new PDPage object
PDPageContentStream contentStream = new PDPageContentStream(documentSource, page, true, true);
PDFont font1 = PDType1Font.HELVETICA;
float startY = page.getMediaBox().getUpperRightY();
float factor = 2.83f;
page.getStream();
// add text
contentStream.beginText();
contentStream.setFont(font1, 10);
contentStream.newLineAtOffset(factor * 60, startY - (factor * 53));
contentStream.showText("test text" + i);
contentStream.endText();
contentStream.close();
}

Cant scan display image charset qr zxing android

Sorry for my english. I cant scan qr image, I have this "???????". I use zxing library. I try but not success. Bellow my code. String equals russian charset. I don't know why scan instance symbol to ??????.
final QRCodeWriter writer = new QRCodeWriter();
ImageView tnsd_iv_qr = (ImageView)findViewById(R.id.qrImage);
Charset charset = Charset.forName("UTF-8");
CharsetEncoder encoder = charset.newEncoder();
byte[] b = null;
try {
// Convert a string to UTF-8 bytes in a ByteBuffer
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(summ.getText().toString() + "/"
+ getNumber.substring(1) + "/"
+ getName + "/"
+ getIdDepartament + "/"
+ getIdUser + "/"
+ getSpinnerItem));
b = bbuf.array();
} catch (CharacterCodingException e) {
//
}
String data;
try {
data = new String(b, "UTF-8");
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
ByteMatrix bitMatrix = writer.encode( data
,BarcodeFormat.QR_CODE, 512, 512, hints);
int width = 512;
int height = 512;
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (bitMatrix.get(x, y)==0)
bmp.setPixel(x, y, Color.BLACK);
else
bmp.setPixel(x, y, Color.WHITE);
}
}
tnsd_iv_qr.setImageBitmap(bmp);
} catch (WriterException | UnsupportedEncodingException e) {
e.printStackTrace();
}
I fix this line
data = new String(b, "ISO-8859-1");
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
hints.put(EncodeHintType.CHARACTER_SET, "ISO-8859-1");
and its work!

How to write an image on disk from blob?

I am tring to create an image file from database on disk. I wrote the following code:
{
oracle.sql.BLOB blob1 = (BLOB) rs.getBlob(1);
//fillFilePath is file path
File blobFile = new File(fillFilePath);
String checkExe[]=fillFilePath.split("\\.");
FileOutputStream outStream = new FileOutputStream(blobFile);
InputStream inStream = blob1.getBinaryStream();
int length = -1;
int size = blob1.getBufferSize();
byte[] buffer = new byte[size];
BufferedImage image = ImageIO.read( inStream );
System.out.println("Inside image upload");
System.out.println("Inside image jpg");
ImageIO.write(image, "JPG", outStream);
But it is not working.
Please give me any suggestions?
try:
BLOB image = ((OracleResultSet) rs).getBLOB("image");
blobLength = image.length();
chunkSize = image.getChunkSize();
binaryBuffer = new byte[chunkSize];
for (position = 1; position <= blobLength; position += chunkSize)
{
bytesRead = image.getBytes(position, chunkSize, binaryBuffer);
outputFileOutputStream.write(binaryBuffer, 0, bytesRead);
totbytesRead += bytesRead;
totbytesWritten += bytesRead;
}
BufferedImage bi= ImageIO.read(obj.getPhoto().getBinaryStream());//photo is Blob.
File outputfile = new File("folderInYourProject\\"+nameVar+".jpg");
ImageIO.write(bi, "jpg", outputfile);

Categories