Apache POI, converting powerpoint slides to images, images are low quality - apache-poi

Here is my code
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
#Service
#Slf4j
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
public class FileConverterService {
public void convertPptToImages() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("Sylon_GuidedPath_Sprint22Deck.ppt").getFile());
Document pdfDocument = new Document();
// PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(""));
FileInputStream is = new FileInputStream(file);
HSLFSlideShow ppt = new HSLFSlideShow(is);
is.close();
Dimension pgsize = ppt.getPageSize();
pdfDocument.setPageSize(new Rectangle((float) pgsize.getWidth(), (float) pgsize.getHeight()));
// convert to images
int idx = 1;
for (HSLFSlide slide : ppt.getSlides()) {
BufferedImage img =
new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setRenderingHint(
RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(
RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(
RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
// clear the drawing area
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// render
slide.draw(graphics);
// save the output
ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpgWriteParam.setCompressionQuality(1f);
jpgWriter.setOutput(new FileImageOutputStream(
new File("slide-" + idx + ".jpg")));
IIOImage outputImage = new IIOImage(img, null, null);
jpgWriter.write(null, outputImage, jpgWriteParam);
jpgWriter.dispose();
idx++;
}
}
I based my code off this documentation, http://poi.apache.org/components/slideshow/how-to-shapes.html#Render
I have tried both jpeg and png, and the image seems to be fairly low resolution and the text is difficult to read compared to the original .ppt. Is there any way to increase the resolution/quality of the images?

What you can try
Applying RenderingHints to the graphics, below is a sample I created comparing the image with/without rendering hint. You can see that the character looks better with rendering hint.
Increase the compression quality for the jpeg image.
Following program demonstrates how to generate image with/without rendering hint and create image with 100% compression quality.
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.FileImageOutputStream;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
public class ImproveSlideConvertToImageQuality {
public static void main(String[] args) throws Exception {
convertPptToImages(true);
convertPptToImages(false);
}
public static void convertPptToImages(boolean withRenderHint) throws Exception {
File file = new File("test.ppt");
String suffix = withRenderHint ? "-with-hint" : "-without-hint";
try (FileInputStream is = new FileInputStream(file); HSLFSlideShow ppt = new HSLFSlideShow(is)) {
Dimension pgsize = ppt.getPageSize();
int idx = 1;
for (HSLFSlide slide : ppt.getSlides()) {
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
if (withRenderHint) {
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.setRenderingHint(
RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
graphics.setRenderingHint(
RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(
RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setRenderingHint(
RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
}
// render
slide.draw(graphics);
final ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
writer.setOutput(new FileImageOutputStream(
new File("slide-" + idx + suffix + ".jpeg")));
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(1f);
// writes the file with given compression level
// from your JPEGImageWriteParam instance
IIOImage image = new IIOImage(img, null, null);
writer.write(null, image, jpegParams);
writer.dispose();
idx++;
}
}
}
}
References:
Controlling Rendering Quality
Setting jpg compression level with ImageIO in Java

Related

Flutter/Mediapipe: how to save a Flutter Canvas/CustomPainter with mediapipe pose outline to an image file?

We are using code shown below from this package package:google_mlkit_pose_detection/google_mlkit_pose_detection.dart (on https://pub.dev/packages/google_mlkit_pose_detection)
to save the phone camera image with mediapipe pose outline to an image file on the phone. The library shows key points of human pose like shoulders and arms with circles and lines using Canvas and CustomPainter. We can see these on the phone screen but we want to save the image and the human pose points to a file in the phone. In other words we want to save the Painting into an image on the phone
A similar question was asked here Flutter: How would one save a Canvas/CustomPainter to an image file? but without the mediapipe component - we tried their solution but it didn't work for us.
The main problem in the code example shown below is that in the line picture = recorder.endRecording(); picture is always null.
import 'dart:math';
import 'dart:typed_data';
import 'dart:ui';
import 'dart:ui' as ui;
import 'package:ace_example/painters/keypoints.dart';
import 'package:flutter/material.dart';
import 'package:google_mlkit_pose_detection/google_mlkit_pose_detection.dart';
import 'coordinates_translator.dart';
class PosePainter extends CustomPainter {
PosePainter(this.poses, this.absoluteImageSize, this.rotation);
final List<Pose> poses;
final Size absoluteImageSize;
final InputImageRotation rotation;
Picture? picture;
final paintMid = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color.fromRGBO(224, 224, 224, 1);
final paintLeft = Paint()
..style = PaintingStyle.fill
..strokeWidth = 2.0
..color = const Color.fromRGBO(255, 138, 0, 1);
final paintRight = Paint()
..style = PaintingStyle.fill
..strokeWidth = 2.0
..color = const Color.fromRGBO(0, 217, 231, 1);
final cycleRadius = 2.0;
final cycleBorderRadius = max(2.0 + 1, 2.0 * 1.2);
final lineWidth = 6.0;
final posePoints = DownwardDogPoints();
#override
void paint(Canvas canvas, Size size) {
final recorder = ui.PictureRecorder();
final canvas = Canvas(
recorder,
Rect.fromPoints(
const Offset(0.0, 0.0), const Offset(0.0, 0.0)));
for (final pose in poses) {
pose.landmarks.forEach((poseType, landmark) {
// draw circle
// white
canvas.drawCircle(
Offset(
translateX(landmark.x, rotation, size, absoluteImageSize),
translateY(landmark.y, rotation, size, absoluteImageSize),
),
cycleBorderRadius,
paintMid);
}
});
}
picture = recorder.endRecording();
}
Future<Image> generateImage() async {
// ui.Image img = (await picture.toImage(384, 683)) as Image;
// return img;
if (picture != null){
ui.Image img = await picture!.toImage(384, 683);
// final pngBytes = await img.toByteData(format: ui.EncodingFormat.png());
ByteData pngBytes = (await img.toByteData(format: ImageByteFormat.png))!;
Uint8List imgList = Uint8List.view(pngBytes.buffer);
return Image.memory(imgList);
} else {
print("Picture is empty");
}
Uint8List imgList = Uint8List.fromList([0, 0, 0 ,0]);
return Image.memory(imgList);
}
#override
bool shouldRepaint(covariant PosePainter oldDelegate) {
return oldDelegate.absoluteImageSize != absoluteImageSize ||
oldDelegate.poses != poses;
}
}

Transcode SVG to JPEG

my picture in SVG format include the latest data 122.6 but in JPEG format the last data point is 122.1
How can I convert the image in svg-format to jpeg-format without the lost of the latest data
renderer ?
padding margins ?
size ?
What is wrong in my code ??
best ghost
package helix;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.fop.svg.PDFTranscoder;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.ext.awt.image.codec.*;
public class genesisMATPIsvg2jpg {
public static void main(String[] args) throws Exception {
//Step -1: We read the input SVG document into Transcoder Input
String svg_URI_input = new File(basePath + "/var/gWebClient/Materialkostenindex2015=100.svg").toURL().toString();
TranscoderInput input_svg_image = new TranscoderInput(svg_URI_input);
//Step-2: Define OutputStream to JPG file and attach to TranscoderOutput
OutputStream jpg_ostream = new FileOutputStream(basePath + "/var/gWebClient/Materialkostenindex2015=100.jpeg");
TranscoderOutput output_jpg_image = new TranscoderOutput(jpg_ostream);
// Step-3: Create JPEGTranscoder and define hints
JPEGTranscoder my_converter = new JPEGTranscoder();
Object jpegQuality1 = new Float(800);
Object jpegQuality2 = new Float(600);
my_converter.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, jpegQuality1);
my_converter.addTranscodingHint(JPEGTranscoder.KEY_HEIGHT, jpegQuality2);
my_converter.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,new Float(0.9));
// Step-4: Write output
my_converter.transcode(input_svg_image, output_jpg_image);
// Step 5- close / flush Output Stream
jpg_ostream.flush();
jpg_ostream.close();
}
}

Excel Conversion of .xls to .xlsx using Java

I am trying to extract test output results in excel format. I want the results to be summarized in neat columns and row formats and want to display results graphically using a Pie chart.
To do this, I have used Apache POI API(Excel edits) and JFreeChart(for Pie chart creation).
I have been able to do all this, and the results are generated in .xls format.
When I tried to convert it to xlsx format after all of this, its doing the job, but the Pie chart and other excel stylings are missed to be written to .xlsx output file.
The code I have used for conversion from .xls to .xlsx is as follows:
package excelFileGenerate6;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//import com.aspose.cells.SaveFormat;
public class conversion_to_xlsx {
public static void main(String[] args) throws InvalidFormatException,
IOException {
String inpFn = "C:\\Users\\Username\\JavaProjects\\workspace\\Sample2\\src\\excelFileGenerate6\\report.xls";
String outFn = "C:\\Users\\Username\\JavaProjects\\workspace\\Sample2\\src\\excelFileGenerate6\\converted_report.xlsx";
FileInputStream in = new FileInputStream(inpFn);
try {
Workbook wbIn = new HSSFWorkbook(in);
File outF = new File(outFn);
if (outF.exists())
outF.delete();
Workbook wbOut = new XSSFWorkbook();
int sheetCnt = wbIn.getNumberOfSheets();
for (int i = 0; i < sheetCnt; i++) {
Sheet sIn = wbIn.getSheetAt(i);
//Sheet sOut = wbOut.getSheet(null);
Sheet sOut = wbOut.createSheet(sIn.getSheetName());
Iterator<Row> rowIt = sIn.rowIterator();
while (rowIt.hasNext()) {
Row rowIn = rowIt.next();
Row rowOut = sOut.createRow(rowIn.getRowNum());
Iterator<Cell> cellIt = rowIn.cellIterator();
while (cellIt.hasNext()) {
Cell cellIn = cellIt.next();
Cell cellOut = rowOut.createCell(
cellIn.getColumnIndex(), cellIn.getCellType());
switch (cellIn.getCellType()) {
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_BOOLEAN:
cellOut.setCellValue(cellIn.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
cellOut.setCellValue(cellIn.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
cellOut.setCellFormula(cellIn.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
cellOut.setCellValue(cellIn.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
cellOut.setCellValue(cellIn.getStringCellValue());
break;
}
{
CellStyle styleIn = cellIn.getCellStyle();
CellStyle styleOut = cellOut.getCellStyle();
styleOut.setDataFormat(styleIn.getDataFormat());
}
cellOut.setCellComment(cellIn.getCellComment());
// HSSFCellStyle cannot be cast to XSSFCellStyle
// cellOut.setCellStyle(cellIn.getCellStyle());
}
}
}
FileOutputStream out = new FileOutputStream(outF);
try {
wbOut.write(out);
} finally {
out.close();
}
} finally {
in.close();
}
}
}
I have generated the excel reports and associated Pie chart using HSSF workbook style which gives the excel output in .xls format. Tried the online help to convert the HSSF objects to XSSF objects , but the pie chart creation gave a sun/image/codec error.
Attaching the Screenshots of code snippets and excel output files.
Any code/direction for converting my .xls results to .xlsx format will highly be of help for me..
Thanks
The code used to create Pie Chart :
package excelFileGenerate6;
import java.awt.Color;
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.PieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.ChartUtilities;
import java.util.Iterator;
public class CreatePieChartExample {
public void createPie(String Filename) throws IOException {
/* Read Excel and the Chart Data */
FileInputStream chart_file_input = new FileInputStream(new File(Filename));
/* Read data into HSSFWorkbook */
HSSFWorkbook my_workbook = new HSSFWorkbook(chart_file_input);
/* This worksheet contains the Pie Chart Data */
HSSFSheet my_sheet = my_workbook.getSheetAt(0);
/* Create JFreeChart object that will hold the Pie Chart Data */
DefaultPieDataset my_pie_chart_data = new DefaultPieDataset();
/* We now iterate over the Excel Workbook data and Populate Pie Chart Data */
/* Create an Iterator object */
Iterator<Row> rowIterator = my_sheet.iterator();
/* Loop through worksheet data and populate Pie Chart Dataset */
String chart_label="a";
Number chart_data=0;
while(rowIterator.hasNext()) {
//Read Rows from Excel document
Row row = rowIterator.next();
//Read cells in Rows and get chart data
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
chart_data=cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_STRING:
chart_label=cell.getStringCellValue();
break;
}
}
/* Add data to the data set */
my_pie_chart_data.setValue(chart_label,chart_data);
}
/* Create a logical chart object with the chart data collected */
JFreeChart myPieChart=ChartFactory.createPieChart("Test Results",my_pie_chart_data,true,true,false);
// Add custom colors
PiePlot plot = (PiePlot) myPieChart.getPlot();
//To create chart labels with only values on pie
PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator("{1}");
plot.setLabelGenerator(gen);
plot.setSectionPaint("Passed", Color.GREEN);
plot.setSectionPaint("Failed", Color.RED);
plot.setSectionPaint("Pending", Color.black);
plot.setSectionPaint("Total Time taken (ms)", Color.pink);
plot.setSectionPaint("Skipped", Color.blue);
plot.setSectionPaint("How many Sub headers are Passed", Color.yellow);
plot.setSectionPaint("Total TC's", Color.CYAN);
/* Specify the height and width of the Pie Chart */
int width=640; /* Width of the chart */
int height=480; /* Height of the chart */
float quality=1; /* Quality factor */
/* We don't want to create an intermediate file. So, we create a byte array output stream
and byte array input stream
And we pass the chart data directly to input stream through this */
/* Write chart as JPG to Output Stream */
ByteArrayOutputStream chart_out = new ByteArrayOutputStream();
ChartUtilities.writeChartAsJPEG(chart_out,quality,myPieChart,width,height);
/* We now read from the output stream and frame the input chart data */
InputStream feed_chart_to_excel=new ByteArrayInputStream(chart_out.toByteArray());
byte[] bytes = IOUtils.toByteArray(feed_chart_to_excel);
/* Add picture to workbook */
int my_picture_id = my_workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
/* We can close Piped Input Stream. We don't need this */
feed_chart_to_excel.close();
/* Close PipedOutputStream also */
chart_out.close();
/* Create the drawing container */
HSSFPatriarch drawing = my_sheet.createDrawingPatriarch();
/* Create an anchor point */
ClientAnchor my_anchor = new HSSFClientAnchor();
/* Define top left corner, and we can resize picture suitable from there */
my_anchor.setCol1(4);
my_anchor.setRow1(5);
/* Invoke createPicture and pass the anchor point and ID */
HSSFPicture my_picture = drawing.createPicture(my_anchor, my_picture_id);
/* Call resize method, which resizes the image */
my_picture.resize();
/* Close the FileInputStream */
chart_file_input.close();
/* Write changes to the workbook */
FileOutputStream out = new FileOutputStream(new File(Filename));
my_workbook.write(out);
out.close();
}
public static void main(String args[]) throws IOException {
CreatePieChartExample chart = new CreatePieChartExample();
chart.createPie("C:\\Users\\user\\JavaProjects\\workspace\\Sample2\\src\\excelFileGenerate6\\report.xls");
}
}
The code used for .xls to .xlsx conversion:
package excelFileGenerate6;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//import com.aspose.cells.SaveFormat;
public class conversion_to_xlsx {
public static void main(String[] args) throws InvalidFormatException,
IOException {
String inpFn = "C:\\Users\\user\\JavaProjects\\workspace\\Sample2\\src\\excelFileGenerate6\\report.xls";
String outFn = "C:\\Users\\user\\JavaProjects\\workspace\\Sample2\\src\\excelFileGenerate6\\converted_report.xlsx";
FileInputStream in = new FileInputStream(inpFn);
try {
Workbook wbIn = new HSSFWorkbook(in);
File outF = new File(outFn);
if (outF.exists())
outF.delete();
Workbook wbOut = new XSSFWorkbook();
int sheetCnt = wbIn.getNumberOfSheets();
for (int i = 0; i < sheetCnt; i++) {
Sheet sIn = wbIn.getSheetAt(i);
//Sheet sOut = wbOut.getSheet(null);
Sheet sOut = wbOut.createSheet(sIn.getSheetName());
Iterator<Row> rowIt = sIn.rowIterator();
while (rowIt.hasNext()) {
Row rowIn = rowIt.next();
Row rowOut = sOut.createRow(rowIn.getRowNum());
Iterator<Cell> cellIt = rowIn.cellIterator();
while (cellIt.hasNext()) {
Cell cellIn = cellIt.next();
Cell cellOut = rowOut.createCell(
cellIn.getColumnIndex(), cellIn.getCellType());
switch (cellIn.getCellType()) {
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_BOOLEAN:
cellOut.setCellValue(cellIn.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
cellOut.setCellValue(cellIn.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
cellOut.setCellFormula(cellIn.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
cellOut.setCellValue(cellIn.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
cellOut.setCellValue(cellIn.getStringCellValue());
break;
}
{
CellStyle styleIn = cellIn.getCellStyle();
CellStyle styleOut = cellOut.getCellStyle();
styleOut.setDataFormat(styleIn.getDataFormat());
}
cellOut.setCellComment(cellIn.getCellComment());
// HSSFCellStyle cannot be cast to XSSFCellStyle
// cellOut.setCellStyle(cellIn.getCellStyle());
}
}
}
FileOutputStream out = new FileOutputStream(outF);
try {
wbOut.write(out);
} finally {
out.close();
}
} finally {
in.close();
}
}
}

Face detection not working in android studio

I'm new to android studio and want to do face detection. The face detector code uses opencv and is written in python. I'm using chaquopy as the python SDK. When i run the app, the face is not detected. It is not showing any error also. Can someone help me out. Below is my MainActivity.java code:
public class MainActivity extends AppCompatActivity {
Button btn;
ImageView iv;
// now take bitmap and bitmap drawable to get image from image view
BitmapDrawable drawable;
Bitmap bitmap;
String imageString="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.submit);
iv = (ImageView)findViewById(R.id.image_view);
if(!Python.isStarted())
Python.start(new AndroidPlatform(this));
final Python py = Python.getInstance();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// on click over button, get image from image view
drawable = (BitmapDrawable)iv.getDrawable();
bitmap = drawable.getBitmap();
imageString = getStringImage(bitmap);
// now in imagestring, we get encoded image string
// now pass this input string to python script
PyObject pyo = py.getModule("myscript");
// calling the main function in python code and passing image string as parameter
PyObject obj = pyo.callAttr("main", imageString);
// obj will return value ie. our image string
String str = obj.toString();
// convert it to byte array
byte data[] = android.util.Base64.decode(str, android.util.Base64.DEFAULT);
// now convert it to bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
//now set this bitmap to imageview
iv.setImageBitmap(bmp);
}
});
}
// function to convert this image into byte array and finally into base 64 string
private String getStringImage(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
// store in byte array
byte[] imageBytes = baos.toByteArray();
// finally encode to string
String encodedImage = android.util.Base64.encodeToString(imageBytes, android.util.Base64.DEFAULT); // Base64.DEFAULT
return encodedImage;
}
}
and the below shown is my python script "myscript.py"
import numpy as np
import cv2
import io
from PIL import Image
import base64
import face_recognition
def main(data):
decoded_data = base64.b64decode(data)
np_data = np.fromString(decoded_data, np.uint8)
img = cv2.imdecode(np_data, cv2.IMREAD_UNCHANGED)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_locations = face_recognition.face_locations(img_gray)
for(top,right,bottom,left) in face_locations:
cv2.rectangle(img_rgb, (left,top),(right,bottom),(0,0,255),8)
# convert this image to PIL
pil_im = Image.fromarray(img_rgb)
#convert this image to byte
buff = io.BytesIO()
pil_im.save(buff, format="PNG")
#converting to base64
img_str = base64.b64encode(buff.getvalue())
return ""+str(img_str, 'utf-8')
My minSdkVersion is 16 and targetSdkVersion is 30.
I'm not understanding what is the problem with this code. Can someone help me.
Thanks in advance.

How to get list of Named range,sheet name and referance formuls using XSSF and SAX (Event API) for large excel file

I'm tring to to read large excel file (size~10MB,.xlsx) .
I'm using below code
Workbook xmlworkbook =WorkbookFactory.create(OPCPackage.openOrCreate(root_path_name_file));
But it's showing Heap memory issue.
I have also seen other solution on StackOverflow some of them given to increase the JVM but i dont want to increase jvm.
Issue 1) We can't use SXSSF (Streaming Usermodel API) because this is only for writing or creating new workbook.
My sole objective to get the number of NamedRange of sheet, Total number of sheet and their sheet name for large excel file.
If the requirement is only to get the named ranges and sheet names, then only the /xl/workbook.xml from the *.xlsx ZIPPackage must be parsed since those informations are all stored there.
This is possible by getting the appropriate PackagePart and parsing the XML from this. For parsing XML my favorite is using StAX.
Example code which gets all sheet names and defined named ranges:
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.XMLEvent;
import javax.xml.namespace.QName;
import java.io.File;
import java.util.regex.Pattern;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class StaxReadOPCPackageParts {
public static void main(String[] args) {
try {
File file = new File("file.xlsx");
OPCPackage opcpackage = OPCPackage.open(file);
//get the workbook package part
PackagePart workbookpart = opcpackage.getPartsByName(Pattern.compile("/xl/workbook.xml")).get(0);
//create reader for package part
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(workbookpart.getInputStream());
List<String> sheetNames = new ArrayList<>();
Map<String, String> definedNames = new HashMap<>();
boolean isInDefinedName = false;
String sheetName = "";
String definedNameName = "";
StringBuffer definedNameFormula = new StringBuffer();
while(reader.hasNext()){ //loop over all XML in workbook.xml
XMLEvent event = (XMLEvent)reader.next();
if(event.isStartElement()) {
StartElement startElement = (StartElement)event;
QName startElementName = startElement.getName();
if(startElementName.getLocalPart().equalsIgnoreCase("sheet")) { //start element of sheet definition
Attribute attribute = startElement.getAttributeByName(new QName("name"));
sheetName = attribute.getValue();
sheetNames.add(sheetName);
} else if (startElementName.getLocalPart().equalsIgnoreCase("definedName")) { //start element of definedName
Attribute attribute = startElement.getAttributeByName(new QName("name"));
definedNameName = attribute.getValue();
isInDefinedName = true;
}
} else if(event.isCharacters() && isInDefinedName) { //character content of definedName == the formula
definedNameFormula.append(((Characters)event).getData());
} else if(event.isEndElement()) {
EndElement endElement = (EndElement)event;
QName endElementName = endElement.getName();
if(endElementName.getLocalPart().equalsIgnoreCase("definedName")) { //end element of definedName
definedNames.put(definedNameName, definedNameFormula.toString());
definedNameFormula = new StringBuffer();
isInDefinedName = false;
}
}
}
opcpackage.close();
System.out.println("Sheet names:");
for (String shName : sheetNames) {
System.out.println("Sheet name: " + shName);
}
System.out.println("Named ranges:");
for (String defName : definedNames.keySet()) {
System.out.println("Name: " + defName + ", Formula: " + definedNames.get(defName));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Resources