generate barcode and show on ImageView in android - android

I am new in android development,and I'm working on android with eclipse now.
I want to generate barcode and show it in ImageView by clicking Button.

Use zxing generate barcodes
Follow these steps and you are good to go.
first, locate core.jar under libs folder.
libs/core.jar
You can download ZXing-2.1.zip from here.
http://code.google.com/p/zxing/downloads/
After unzipping the file, find the jar file.
\ZXing-2.1\zxing-2.1\core\core.jar
And then write your own code like below.
import java.util.EnumMap;
import java.util.Map;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
public class BarcodeExampleActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout l = new LinearLayout(this);
l.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
l.setOrientation(LinearLayout.VERTICAL);
setContentView(l);
// barcode data
String barcode_data = "123456";
// barcode image
Bitmap bitmap = null;
ImageView iv = new ImageView(this);
try {
bitmap = encodeAsBitmap(barcode_data, BarcodeFormat.CODE_128, 600, 300);
iv.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
l.addView(iv);
//barcode text
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setText(barcode_data);
l.addView(tv);
}
/**************************************************************
* getting from com.google.zxing.client.android.encode.QRCodeEncoder
*
* See the sites below
* http://code.google.com/p/zxing/
* http://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/encode/EncodeActivity.java
* http://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/encode/QRCodeEncoder.java
*/
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
}

Related

Trying to create a PDF from a listview

Hello Everyone I'm trying to create a pdf programatically from a set of images. I'm loading images on Listview from array list. after displaying the images on click floating action button I'm willing to create a new PDF file. I'm successfully creating file, Unfortunately I can able to see only one image on the pdf file out of 5 images. For reference purpose here I'm sharing the code which I'm trying to achieve. Please help me in creating and displaying list of images on PDF
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.pdf.PdfDocument;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.FileHandler;
public class DisplayPreview extends AppCompatActivity {
String TAG = DisplayPreview.class.getName();
ListView imagesLV;
FloatingActionButton fabPDF;
TextView tv_link;
ImageView iv_image;
LinearLayout ll_pdflayout;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
boolean boolean_save;
Bitmap bitmap;
ProgressDialog progressDialog;
ArrayList<String> selectedImagesList;
String targetPdf;
DisplayPreviewAdapter displayPreviewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_preview);
Intent intent = getIntent();
selectedImagesList = intent.getStringArrayListExtra("selectedArray");
fn_permission();
imagesLV = findViewById(R.id.imagesLV);
displayPreviewAdapter = new DisplayPreviewAdapter(this, selectedImagesList);
imagesLV.setAdapter(displayPreviewAdapter);
fabPDF = findViewById(R.id.fabPDF);
fabPDF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boolean_save) {
Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
intent.putExtra("pdfFile", targetPdf);
startActivity(intent);
} else {
if (boolean_permission) {
progressDialog = new ProgressDialog(DisplayPreview.this);
progressDialog.setMessage("Please wait");
bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
makePDF();
} else {
}
makePDF();
}
}
});
}
private void makePDF() {
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = displaymetrics.heightPixels;
float width = displaymetrics.widthPixels;
int convertHighet = (int) hight, convertWidth = (int) width;
// Resources mResources = getResources();
// Bitmap bitmap = BitmapFactory.decodeResource(mResources, R.drawable.img_1);
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(getBitmapFromView(imagesLV), convertWidth, convertHighet, true);
// bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0, null);
document.finishPage(page);
// write the document content
// String targetPdf = "/sdcard/test.pdf";
targetPdf = "mnt/sdcard/testing_1.pdf";
File filePath = new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
boolean_save = true;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
}
// close the document
document.close();
}
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
public static Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(DisplayPreview.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(DisplayPreview.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
if ((ActivityCompat.shouldShowRequestPermissionRationale(DisplayPreview.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(DisplayPreview.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
}
After hours of Struggle I found my own answer in creating multiple pages in a single PDF using android also image annotating with text here is the following source code
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
public class DisplayPreview extends AppCompatActivity {
String TAG = DisplayPreview.class.getName();
ListView imagesLV;
FloatingActionButton fabPDF;
Bitmap anImage;
TextView tv_link;
ImageView iv_image;
LinearLayout ll_pdflayout;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
boolean boolean_save;
Bitmap bitmap;
ProgressDialog progressDialog;
ArrayList<String> selectedImagesList;
String targetPdf;
DisplayPreviewAdapter displayPreviewAdapter;
String familyStatus, userNameStr;
public static final Integer[] IMAGES = {
R.drawable.img_1,
R.drawable.img_2,
R.drawable.img_3,
R.drawable.img_4,
R.drawable.img_5,
R.drawable.img_6,
R.drawable.img_7
// ,R.drawable.img_8,
// R.drawable.img_9
};
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_preview);
Intent intent = getIntent();
selectedImagesList = intent.getStringArrayListExtra("selectedArray");
familyStatus = intent.getStringExtra("familyStatus");
userNameStr = intent.getStringExtra("userNameStr");
targetPdf = "mnt/sdcard/testing_2.pdf";
imagesLV = findViewById(R.id.imagesLV);
displayPreviewAdapter = new DisplayPreviewAdapter(this, selectedImagesList, IMAGES);
// imagesLV.setAdapter(displayPreviewAdapter);
fabPDF = findViewById(R.id.fabPDF);
Drawable myDrawable = getResources().getDrawable(R.drawable.img_1);
anImage = ((BitmapDrawable) myDrawable).getBitmap();
createMultiPagePDF();
fabPDF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boolean_save) {
Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
intent.putExtra("pdfFile", targetPdf);
startActivity(intent);
} else {
if (boolean_permission) {
progressDialog = new ProgressDialog(DisplayPreview.this);
progressDialog.setMessage("Please wait");
// bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
// makePDF();
createMultiplePDF();
} else {
}
createMultiplePDF();
// makePDF();
}
}
});
}
private void createMultiPagePDF() {
pDialog = new ProgressDialog(DisplayPreview.this);
pDialog.setMessage("Please wait...Creating Invitation");
pDialog.setCancelable(false);
pDialog.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
if (boolean_save) {
Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
intent.putExtra("pdfFile", targetPdf);
startActivity(intent);
} else {
if (boolean_permission) {
progressDialog = new ProgressDialog(DisplayPreview.this);
progressDialog.setMessage("Please wait");
// bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
// makePDF();
createMultiplePDF();
} else {
}
createMultiplePDF();
// makePDF();
}
}
}, 4000);
}
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
public void createMultiplePDF() {
// targetPdf = "mnt/sdcard/testing_1.pdf";
targetPdf = "mnt/sdcard/" + userNameStr + ".pdf";
File filePath = new File(targetPdf);
// Document document = new Document();
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
// step 2
PdfWriter writer = null;
try {
writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// step 3
document.open();
// step 4
try {
Drawable myDrawable = null;
for (int i = 0; i < selectedImagesList.size(); i++) {
//
String imagePath = selectedImagesList.get(i).replaceAll("^\"|\"$", "");
Log.i(TAG, "Image Path is :: 271 :: " + imagePath);
// if (imagePath.equals("R.drawable.img_8")) {
if (imagePath.equals(userNameStr)) {
Bitmap processedBitmap = ProcessingBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
processedBitmap.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_2")) {
myDrawable = getResources().getDrawable(R.drawable.img_2);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_3")) {
myDrawable = getResources().getDrawable(R.drawable.img_3);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_4")) {
myDrawable = getResources().getDrawable(R.drawable.img_4);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_5")) {
myDrawable = getResources().getDrawable(R.drawable.img_5);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_6")) {
myDrawable = getResources().getDrawable(R.drawable.img_6);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_7")) {
myDrawable = getResources().getDrawable(R.drawable.img_7);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
/* if (imagePath.equals("R.drawable.img_8")) {
myDrawable = getResources().getDrawable(R.drawable.img_8);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
} if (imagePath.equals("R.drawable.img_9")) {
myDrawable = getResources().getDrawable(R.drawable.img_9);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}*/
}
document.close();
pDialog.dismiss();
Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
intent.putExtra("pdfFile", targetPdf);
startActivity(intent);
finish();
} catch (DocumentException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressLint("ResourceAsColor")
private Bitmap ProcessingBitmap() {
Resources resources = DisplayPreview.this.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bm1 = BitmapFactory.decodeResource(getResources(), R.drawable.img_1);
Bitmap.Config config = bm1.getConfig();
if (config == null) {
config = Bitmap.Config.ARGB_8888;
}
// newBitmap = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(), config);
anImage = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(), config);
// Canvas newCanvas = new Canvas(newBitmap);
Canvas newCanvas = new Canvas(anImage);
newCanvas.drawBitmap(bm1, 0, 0, null);
String captionString = userNameStr.trim();
if (captionString != null) {
TextPaint paintText = new TextPaint(Paint.ANTI_ALIAS_FLAG);
paintText.setColor(R.color.wedding_guest_name);
paintText.setTextSize(100);
paintText.setStyle(Paint.Style.FILL_AND_STROKE);
paintText.setTextAlign(Paint.Align.CENTER);
int textWidth = newCanvas.getWidth() - (int) (250 * scale);
StaticLayout textLayout = new StaticLayout(
captionString, paintText, textWidth, Layout.Alignment.ALIGN_LEFT, 1.0f, 1.4f, false);
Rect rectText = new Rect();
paintText.getTextBounds(captionString, 0, captionString.length(), rectText);
float xPos = (newCanvas.getWidth() / 2.16f);
float yPos = (int) ((newCanvas.getHeight() / 2.4) - ((paintText.descent() + paintText.ascent()) / 3.0));
float x = newCanvas.getWidth()/2;
// float y = newCanvas.getHeight()/2;
// draw text to the Canvas center
newCanvas.save();
// newCanvas.translate(xPos, yPos);
newCanvas.translate(x, yPos);
textLayout.draw(newCanvas);
newCanvas.restore();
// drawMultiLineText(captionString,xPos, yPos, paintText, newCanvas);
// newCanvas.drawText(captionString,xPos, yPos, paintText);
} else {
Toast.makeText(getApplicationContext(),
"caption empty!",
Toast.LENGTH_LONG).show();
}
// return newBitmap;
return anImage;
}
}
I suggest you to use iTextPdf to create pdf in easy way
compile 'com.itextpdf:itextg:5.5.10'
Add itextpdf library into your project app build.gradle file
implementation 'com.itextpdf:itext-pdfa:5.5.5'
Below is the code to create pdf file and add image into each cell in table
Document document = new Document(PageSize.A4, 10, 10, 10, 10);
try {
File f = new File(Environment.getExternalStorageDirectory() + "/*foldername*");
f = new File(f.getAbsolutePath() + "/" + * filename *);
if (!f.exists()) {
f.mkdir();
}
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(f.getAbsolutePath() + "/" + * filename * +".pdf"));
document.open();
for (int l = 0; l < list.size; l++) {
PdfPTable thirdPart = new PdfPTable(col);
thirdPart.getDefaultCell().setBorder(Rectangle.NO_BORDER);
thirdPart.setWidthPercentage(100.0f);
thirdPart.setHorizontalAlignment(Element.ALIGN_LEFT);
Image str = list.get(l);
PdfPCell imageCell = new PdfPCell(str);
thirdPart.addCell(imageCell);
}
document.add(thirdPart);
} catch (Exception e) {
e.printStackTrace();
}
document.close();

How to recognize special markers on image in Android?

I want to put buttons on layout by special markers (f.g. small circles).
See picture below:
Final result maybe like this:
Whats the right way to do that? Most libraries and SDKs for image recognition works with images from camera (almost in real time). In my case I have static image and its remain only recognize the special markers and then put buttons.
I found this solve: Detect Circle in image using OpenCV in Android and used it in my project. This works fine, but I have another problem (see this question: How to convert Mat coordinates to Layout coordinates?)
package com.example.aboev.matrix_sample;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.ConstraintSet;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class FloorPlanActivity extends AppCompatActivity {
Mat matBackground;
Mat grayMatBackground;
int colorChannels = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_floor_plan);
ImageView imageViewFloorPlan = findViewById(R.id.imageViewFloorPlan);
FileInputStream imageFileInputStream;
Context context = this;
// this double dimension array will contain X,Y positions of recognized circles
ArrayList<ArrayList<Integer>> coordinates = new ArrayList<>();
ConstraintLayout layout = findViewById(R.id.scrollingFloorPlanLayout);
try {
imageFileInputStream = context.openFileInput(getString(R.string.png_image_file_name));
Bitmap imageFloorPlan = BitmapFactory.decodeStream(imageFileInputStream);
imageViewFloorPlan.setImageBitmap(imageFloorPlan);
matBackground = new Mat(imageFloorPlan.getHeight(), imageFloorPlan.getWidth(),
CvType.CV_8UC1);
grayMatBackground = new Mat(imageFloorPlan.getHeight(), imageFloorPlan.getWidth(),
CvType.CV_8UC1);
Utils.bitmapToMat(imageFloorPlan, matBackground);
colorChannels = (matBackground.channels() == 3) ?
Imgproc.COLOR_BGR2GRAY : ((matBackground.channels() == 4) ?
Imgproc.COLOR_BGRA2GRAY : 1);
Imgproc.cvtColor(matBackground, grayMatBackground, colorChannels);
Imgproc.GaussianBlur(grayMatBackground, grayMatBackground,
new Size(9, 9), 2, 2);
double dp = 1.5d;
double minDist = grayMatBackground.rows() / 16;
int minRadius = 10;
int maxRadius = 20;
double param1 = 70;
double param2 = 50;
Mat circles = new Mat(imageViewFloorPlan.getWidth(), imageViewFloorPlan.getHeight(),
CvType.CV_8UC1);
Imgproc.HoughCircles(grayMatBackground, circles,
Imgproc.CV_HOUGH_GRADIENT, dp, minDist, param1,
param2, minRadius, maxRadius);
int numberOfCircles = (circles.rows() == 0) ? 0 : circles.cols();
if (circles.empty() || circles.get(0, 0).length == 1) {
Toast.makeText(context, getString(R.string.msg_circles_not_found),
Toast.LENGTH_SHORT).show();
} else {
for (int i=0; i<numberOfCircles; i++) {
double[] circleCoordinates = circles.get(0, i);
final int x = (int) circleCoordinates[0], y = (int) circleCoordinates[1];
Point center = new Point(x, y);
int radius = (int) circleCoordinates[2];
Imgproc.circle(matBackground, center, radius, new Scalar(0,
255, 0), 4);
Imgproc.rectangle(matBackground, new Point(x - 5, y - 5),
new Point(x + 5, y + 5),
new Scalar(0, 128, 255), -1);
coordinates.add( new ArrayList<Integer>() {{ add((int) x); add((int) y); }} );
}
}
Utils.matToBitmap(matBackground, imageFloorPlan);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
imageFileInputStream = context.openFileInput(getString(R.string.table_image_file));
if (!coordinates.isEmpty()) createImgButton(context, BitmapFactory.decodeStream(imageFileInputStream), coordinates);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// This method creates buttons in the centers of recognized circles
private void createImgButton(Context context, Bitmap foregroundImage, ArrayList<ArrayList<Integer>> coordinates) {
ConstraintLayout layout = findViewById(R.id.scrollingFloorPlanLayout);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(layout);
for (int i = 0; i < coordinates.size(); i++) {
ImageButton btn = new ImageButton(context);
btn.setImageBitmap(foregroundImage);
btn.setId(ViewIdGenerator.generateViewId());
layout.addView(btn);
constraintSet.clone(layout);
// I tried to get real coordinate like this:
double x = (coordinates.get(i).get(1) * 1080) / 480;
double y = (coordinates.get(i).get(0) * 1920) / 640;
constraintSet.connect(btn.getId(), constraintSet.TOP, layout.getId(), constraintSet.TOP, (int) x);
constraintSet.connect(btn.getId(), constraintSet.START, layout.getId(), constraintSet.START, (int) y);
constraintSet.applyTo(layout);
}
}
}
It looks like this:

I need to Generate barcode image with label in UPC A format on it in android

Sample UPC A Format image attached
I used Zxing libray.it's generating barcode image without label but i need with label as like attached image..
Code i used to generate image:
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
Writer codeWriter;
if (barcodeFormat == BarcodeFormat.QR_CODE) {
codeWriter = new QRCodeWriter();
} else if (barcodeFormat == BarcodeFormat.CODE_128) {
codeWriter = new Code128Writer();
} else if (barcodeFormat == BarcodeFormat.UPC_A) {
codeWriter = new UPCAWriter();
} else {
throw new RuntimeException("Format Not supported.");
}
BitMatrix byteMatrix = codeWriter.encode(
codeData,
barcodeFormat,
codeWidth,
codeHeight,
hintMap
);
int width = byteMatrix.getWidth();
int height = byteMatrix.getHeight();
Bitmap imageBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
imageBitmap.setPixel(i, j, byteMatrix.get(i, j) ? BLACK : Color.TRANSPARENT);
}
}
return imageBitmap;
Please help me on this
using below library you have to generate QRCode in android.This library is built on Zxing library.
https://github.com/kenglxn/QRGen
Android Code:
Bitmap myBitmap = QRCode.from("www.example.org").bitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
For barcode with lable use below code and also put core-3.0.1.jar zxing jar in lib folder:
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import java.util.EnumMap;
import java.util.Map;
public class BarcodeExampleActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout l = new LinearLayout(this);
l.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
l.setOrientation(LinearLayout.VERTICAL);
setContentView(l);
// barcode data
String barcode_data = "123456";
// barcode image
Bitmap bitmap = null;
ImageView iv = new ImageView(this);
try {
bitmap = encodeAsBitmap(barcode_data, BarcodeFormat.CODE_128, 600, 300);
iv.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
l.addView(iv);
//barcode text
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setText(barcode_data);
l.addView(tv);
}
/**************************************************************
* getting from com.google.zxing.client.android.encode.QRCodeEncoder
*
* See the sites below
* http://code.google.com/p/zxing/
* http://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/encode/EncodeActivity.java
* http://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/encode/QRCodeEncoder.java
*/
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
}

How to save a frame using google vision face detect

I am trying to following the google-vision face-tracker sample listed in here. I would like to know how to get the number of face detected by the application and how to save a frame to the phone memory, is it possible from the application ?
Yes, you can use the following code:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.media.FaceDetector;
import android.util.SparseArray;
import com.google.android.gms.vision.Frame;
import com.piisoft.upecfacerecognition.utility.Image;
import java.io.File;
import java.util.List;
public class extractFacesFromImage {
public extractFacesFromImage(String imagePath , String OutPutPath , Context context){
File folder = new File(OutPutPath);
if(!folder.exists()){
folder.mkdirs();
}
detectFacesInImage(imagePath , OutPutPath, context);
}
private void detectFacesInImage(String imagePath , String OutPutPath){
//ImageWindow[] imageWindow = null;
Bitmap image = Image.bitmapFromJpg(imagePath);
FaceDetector.Face[] faces = detectFaces(image);
for(FaceDetector.Face fs:faces)
{
if(fs == null){continue;}
PointF midPoint=new PointF();
fs.getMidPoint(midPoint);
float eyeDistance=fs.eyesDistance();
int left = (int)(midPoint.x - (float)(1.4 * eyeDistance));
int top = (int)(midPoint.y - (float)(1.8 * eyeDistance));
Bitmap bmFace = Bitmap.createBitmap(image, (int) left, (int) top, (int) (2.8 * eyeDistance), (int) (3.6 * eyeDistance));
Bitmap bmp= bmFace.createBitmap(bmFace.getWidth(), bmFace.getHeight(), Bitmap.Config.ARGB_8888);
Image.saveBitmapToJpg(bmp,OutPutPath, "face_" + System.currentTimeMillis() +".jpg" ,256,256);
//ImageWindow Iw = new ImageWindow(fs.)
}
//return imageWindow;
}
private void detectFacesInImage(String imagePath , String OutPutPath, Context context){
//ImageWindow[] imageWindow = null;
Bitmap image = Image.bitmapFromJpg(imagePath);
if(image == null){
return;
}
SparseArray<com.google.android.gms.vision.face.Face> faces = detectFaces(image,context);
for (int i = 0; i < faces.size(); ++i) {
com.google.android.gms.vision.face.Face face = faces.valueAt(i);
if(face == null){continue;}
try {
Bitmap bmFace = Bitmap.createBitmap(image, (int) face.getPosition().x, (int) face.getPosition().y, (int) face.getWidth(), (int) face.getHeight());
Image.saveBitmapToJpg(bmFace, OutPutPath, "face_" + System.currentTimeMillis() + ".jpg",256);
}
catch (Exception e){
e.printStackTrace();
}
}
new File(imagePath).delete();
}
private SparseArray<com.google.android.gms.vision.face.Face> detectFaces(Bitmap image , Context context) {
int h = image.getHeight();
int w = image.getWidth();
int max = 10;
Frame frame = new Frame.Builder().setBitmap(image).build();
com.google.android.gms.vision.face.FaceDetector detector = new com.google.android.gms.vision.face.FaceDetector.Builder(context)
.setTrackingEnabled(false)
.setLandmarkType(com.google.android.gms.vision.face.FaceDetector.ALL_LANDMARKS)
.build();
SparseArray<com.google.android.gms.vision.face.Face> faces = detector.detect(frame);
detector.release();
return faces;
}
private FaceDetector.Face[] detectFaces(Bitmap image ) {
int h = image.getHeight();
int w = image.getWidth();
int max = 10;
FaceDetector detector = new FaceDetector(w, h, max);
FaceDetector.Face[] faces = new FaceDetector.Face[max];
int facesFound = detector.findFaces(image, faces);
return faces;
}
}

Mat doesn't work with bitmap in Android OpenCV

I'm trying to implement some filters in a Bitmap with OpenCV in Android, the first step is detect a face and split in 2 images (eyes).
But when I try implement a Mat function to do some Image processing it die.
The error text is this:
08-05 17:54:58.659: E/AndroidRuntime(11005): java.lang.UnsatisfiedLinkError: n_Mat
And the code is this, I'm getting crazy with OpenCV.
package org.opencv.samples.puzzle15;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class Puzzle15Activity extends Activity {
private static final String TAG = "Sample::TestFilter::Activity";
private ImageView face;
private ImageView leftEyeImg;
private ImageView rightEyeImg;
private Bitmap fL;
private Bitmap fR;
FaceDetector fD;
FaceDetector.Face[] faceArray;
Bitmap rightEye;
Bitmap leftEye;
int y;
private int mGameWidth;
private int mGameHeight;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
//starEverything();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Log.i(TAG, "Ejecutando onCreate");
LinearLayout layout = new LinearLayout(this);
face = new ImageView(this);
face.setImageResource(R.drawable.asd);
leftEyeImg = new ImageView(this);
rightEyeImg = new ImageView(this);
int max = 5;
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inPreferredConfig = Bitmap.Config.RGB_565;
bfo.inScaled = false;
bfo.inDither = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.face1, bfo);
int w = bitmap.getWidth();
int h = bitmap.getHeight();
FaceDetector fd = new FaceDetector(w, h, max);
Face[] faces = new Face[max];
int c = fd.findFaces(bitmap, faces);
Log.d("TAG", "FACES: "+c);
for (int i=0;i<c;i++) {
Log.d("TAG", Float.toString(faces[i].eyesDistance()));
}
PointF fpx;
fpx = new PointF();
faces[0].getMidPoint(fpx);
float fds = faces[0].eyesDistance();
Log.d("TAG", "x: "+fpx.x);
Log.d("TAG", "y: "+fpx.y);
Log.d("TAG", "fsd: "+fds);
Log.d("TAG", "w: "+w);
Log.d("TAG", "h: "+h);
fL =cropBitmap1(bitmap,fpx.x, fpx.y, fds, fds);
fR =cropBitmap1(bitmap, fpx.x-fpx.y/2, fpx.y, fds, fds);
rightEyeImg.setImageBitmap(fR);
leftEyeImg.setImageBitmap(fL);
layout.addView(leftEyeImg);
layout.addView(rightEyeImg);
setContentView(layout);
someFilter(fL);
}
public void someFilter(Bitmap a){
synchronized (this){
Mat tmp = new Mat (a.getWidth(), a.getHeight(), CvType.CV_8UC1);
Utils.bitmapToMat(a, tmp);
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_RGB2GRAY);
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_GRAY2RGB, 4);
Utils.matToBitmap(tmp, a);
}
}
private Bitmap cropBitmap1(Bitmap source, Float x, Float y, Float h, Float w)
{
Bitmap cropped = Bitmap.createBitmap(source, Math.round(x),Math.round(y)-Math.round(h)/4, Math.round(h), Math.round(h)/2);
return cropped;
}
}
I think you should check if any faces detected before lines
faces[0].getMidPoint(fpx);
float fds = faces[0].eyesDistance();
Second thind I've noticed is
Mat tmp = new Mat (a.getWidth(), a.getHeight(), CvType.CV_8UC1);
You should change rows and cols for matrix:
Mat tmp = new Mat (a.getHeight(),a.getWidth(), CvType.CV_8UC1);

Categories

Resources