Transcode SVG to JPEG - svg

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

Related

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.

Apache POI, converting powerpoint slides to images, images are low quality

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

How do I integrate QR code reading application to Sony SmartEyeGlass?

We are developing an application for Sony SmartEyeGlass. Firstly, we created it with Android Studio and android tablet.Now, we are working with Sample Camera Extension sample to integrate it our Project. But there is a lot of details. Someone can help about this subject?
The Sample Camera extension is a great place to start building your QR code reader. In the SampleCameraControl.java there is a function called cameraEventOperation. In this function you will see an example of how to pull the camera data down in to a bitmap. Here is the code for reference:
private void cameraEventOperation(CameraEvent event) {
if ((event.getData() != null) && ((event.getData().length) > 0)) {
data = event.getData();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
You can take this data and send it to your QR code reader to scan for QR codes. Let me know if this helps!
----- Update ----
You can use a function like this to pass a bitmap to the Google Zxing library. Use should put this in something like an Async task:
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
//This function sends the provided bitmap to Google Zxing
public static String readBarcodeImage(Bitmap bMap) {
String contents = null;
int[] intArray = new int[bMap.getWidth()*bMap.getHeight()];
//copy pixel data from the Bitmap into the 'intArray' array
bMap.getPixels(intArray, 0, bMap.getWidth(), 0, 0, bMap.getWidth(), bMap.getHeight());
LuminanceSource source = new RGBLuminanceSource(bMap.getWidth(), bMap.getHeight(), intArray);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new MultiFormatReader();// use this otherwise ChecksumException
try {
Hashtable<DecodeHintType,Object> hints=new Hashtable<DecodeHintType,Object>();
hints.put(DecodeHintType.TRY_HARDER,Boolean.TRUE);
Vector<BarcodeFormat> decodeFormats = new Vector<BarcodeFormat>();
decodeFormats.add(BarcodeFormat.QR_CODE);
hints.put(DecodeHintType.POSSIBLE_FORMATS,decodeFormats);
Result result = reader.decode(bitmap, hints);
BarcodeFormat format = result.getBarcodeFormat();
contents = result.getText() + " : "+format.toString();
} catch (NotFoundException e) { e.printStackTrace(); }
catch (ChecksumException e) { e.printStackTrace(); }
catch (FormatException e) { e.printStackTrace(); }
return contents;
}

Error executing data process; Caused by: Premature end of file. (in groovy script); Caused by: Premature end of file

I am getting the above error in the groovy script in boomi Please help me!! Below is the code.I am trying to format to xml. Data process is throwing this error.
import java.util.Properties;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import com.boomi.execution.ExecutionUtil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
// Retrieve a handle to the Logger
logger = ExecutionUtil.getBaseLogger();
InputStream io = dataContext.getStream(0);
Properties props = dataContext.getProperties(0);
BufferedReader br = new BufferedReader(new InputStreamReader(io));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
def text = sb.toString();
text = text.replaceAll('&lt', '')
text = text.replaceAll('&gt', '')
def xmlStream = new XmlParser().parseText(text);
def data = xmlStream.data;
def result = "<records>"
for (child in data) {
def stringWriter = new StringWriter()
new XmlNodePrinter(new PrintWriter(stringWriter)).print(child)
result = result + stringWriter.toString();
}
result = result + "</records>"
def childIO = new ByteArrayInputStream(result.getBytes());
dataContext.storeStream(childIO, props);
Unless the input data with profile is given in this question, it will be difficult to answer it. However from the code, it seems that an extra parent node is being created to the input XML. This can easily be achieved by a Message component in Boomi. Use a message shape and input the following: <records>{1}</records> and form the parameters option in Message shape, use Current Data. This will give the same output for all your documents which you are trying to achieve from code. In case if it does not fulfill your requirements please provide more details like input profile with fields and expected output.

Resources