Print Textviews and webview from fragment - android

I'm using such code for creating pdf from webview
PrintManager printManager = (PrintManager) this
.getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter("PDF");
printManager.print("PDF", printAdapter,
new PrintAttributes.Builder().build());
what should I do, to add to this pdf creation some TextView because I need to add additional fields to my fragment?
Know about itextg, but I need something free.

Choose an option to implement fields as html in webview

You can get a bitmap out of the webview and then draw the textview on the bitmap, using the bitmap canvas.
From there, you can convert the bitmap into a pdf and share the pdf.
Here is the code for converting a webview into a bitmap, and also converting a bitmap into a pdf and then sharing it, asking the user to select its printer app:
public static void sharePdfFile(WebView webView, Context context)
{
Bitmap bitmap = webviewToBitmap( webView );
PrintedPdfDocument pdf = bitmapToPdf( bitmap, context );
File file = pdfToFile( pdf, context );
shareFile( file,"application/pdf", context );
}
private static void shareFile(File file, String contentType, Context context)
{
Uri uri = FileProvider.getUriForFile(
context,
context.getPackageName() + ".fileprovider",
file);
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType(contentType);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Toast.makeText(
context,
"Choose your printer app",
Toast.LENGTH_LONG
).show();
context.startActivity( shareIntent );
}
private static File pdfToFile(PrintedPdfDocument printedPdfDocument, Context context)
{
File file = new File(context.getFilesDir(), "share.pdf");
try {
FileOutputStream outputStream = new FileOutputStream(file);
printedPdfDocument.writeTo(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
printedPdfDocument.close();
return file;
}
private static PrintedPdfDocument bitmapToPdf(Bitmap bitmap, Context context)
{
PrintAttributes printAttributes = new PrintAttributes.Builder()
.setColorMode(PrintAttributes.COLOR_MODE_COLOR)
.setMediaSize(PrintAttributes.MediaSize.ISO_A4)
.setMinMargins(PrintAttributes.Margins.NO_MARGINS)
.setResolution(new PrintAttributes.Resolution("1", "label", 300, 300))
.build();
PrintedPdfDocument printedPdfDocument = new PrintedPdfDocument(context, printAttributes);
PdfDocument.Page pdfDocumentPage = printedPdfDocument.startPage(1);
Canvas pdfCanvas = pdfDocumentPage.getCanvas();
bitmap = scaleBitmapToHeight(bitmap, pdfCanvas.getHeight());
pdfCanvas.drawBitmap(bitmap, 0f, 0f, null);
printedPdfDocument.finishPage(pdfDocumentPage);
return printedPdfDocument;
}
private static Bitmap webviewToBitmap(WebView webView) {
webView.measure(
View.MeasureSpec.makeMeasureSpec(
0,
View.MeasureSpec.UNSPECIFIED
),
View.MeasureSpec.makeMeasureSpec(
0,
View.MeasureSpec.UNSPECIFIED
)
);
int webViewWidth = webView.getMeasuredWidth();
int webViewHeight = webView.getMeasuredHeight();
webView.layout(0,0, webViewWidth, webViewHeight );
Bitmap bitmap = Bitmap.createBitmap(webViewWidth, webViewHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(bitmap, 0, bitmap.getHeight(), new Paint());
webView.draw(canvas);
return bitmap;
}
private static Bitmap scaleBitmapToHeight(Bitmap bitmap, int maxHeight) {
int height = bitmap.getHeight();
if(height > maxHeight) {
int width = bitmap.getWidth();
float scalePercentage = ((float)maxHeight) / height;
return Bitmap.createScaledBitmap(bitmap, (int) (width * scalePercentage), maxHeight, false);
}
return bitmap;
}

Related

How to generate PDF file for the whole listview android

I have created the bitmap and have created the pdf file for the bitmap.
but I need to generate pdf for the whole listview which is scrollable.
Given below is is my code, please give me any suggestion, thanks in advance!!
I could not find the pdf creating application which could copy the entire UI or say in my case the entire listview into the pdf. If anybody could suggest what could be done in this case I would be grateful.
public class MainActivity extends AppCompatActivity {
private Button btn;
private LinearLayout llScroll;
private Bitmap bitmap;
private ListView listView;
ArrayList<String> myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
llScroll = findViewById(R.id.llScroll);
listView = (ListView)findViewById(R.id.listView);
String[] names= new String[]{"One","Two","Three","Four","Five","Six","Seven","One","Two","Three","Four","Five","Six","Seven"};
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,names);
listView.setAdapter(arrayAdapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("size"," "+llScroll.getWidth() +" "+llScroll.getWidth());
bitmap = loadBitmapFromView(llScroll, llScroll.getWidth(), llScroll.getHeight());
createPdf();
}
});
}
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;
}
private void createPdf(){
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = displaymetrics.heightPixels ;
float width = displaymetrics.widthPixels ;
int convertHighet = (int) hight, convertWidth = (int) width;
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(bitmap, convertWidth, convertHighet, true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0 , null);
document.finishPage(page);
// write the document content
String targetPdf = "/sdcard/pdffromScroll.pdf";
File filePath;
filePath = new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
}
// close the document
document.close();
Toast.makeText(this, "PDF of Scroll is created!!!", Toast.LENGTH_SHORT).show();
openGeneratedPDF();
}
private void openGeneratedPDF(){
File file = new File("/sdcard/pdffromScroll.pdf");
if (file.exists())
{
Intent intent=new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try
{
startActivity(intent);
}
catch(ActivityNotFoundException e)
{
Toast.makeText(MainActivity.this, "No Application available to view pdf", Toast.LENGTH_LONG).show();
}
}
}}

webview into pdf using PdfDocument

I want to convert webview into PDF document and save the document in external storage. The pdf should be similar to the one which we can generate we we print the webview and chose save as pdf instead of printing.
Code for Webview:
WebView ww = (WebView) findViewById(R.id.ww);
ww.getSettings().setUserAgentString("Mozilla/5.0 Chrome/53.0.2785.116");
ww.getSettings().setDefaultTextEncodingName("en-US,en;q=0.8");
WebSettings webSettings = ww.getSettings();
webSettings.setJavaScriptEnabled(true);
ww.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
ww.getSettings().setBuiltInZoomControls(true);
ww.getSettings().setDisplayZoomControls(false);
ww.getSettings().setLoadWithOverviewMode(true);
ww.getSettings().setUseWideViewPort(true);
ww.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
You can convert the webview into a bitmap and then into a PDF document. The advantage of not converting directly to PDF is that you can scale the image to fit the PDF in any way you want.
This code converts a webview into a pdf page and then shares it, asking the user to select his printer app:
public static void sharePdfFile(WebView webView, Context context)
{
Bitmap bitmap = webviewToBitmap( webView );
PrintedPdfDocument pdf = bitmapToPdf( bitmap, context );
File file = pdfToFile( pdf, context );
shareFile( file,"application/pdf", context );
}
private static void shareFile(File file, String contentType, Context context)
{
Uri uri = FileProvider.getUriForFile(
context,
context.getPackageName() + ".fileprovider",
file);
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType(contentType);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Toast.makeText(
context,
"Choose your printer app",
Toast.LENGTH_LONG
).show();
context.startActivity( shareIntent );
}
private static File pdfToFile(PrintedPdfDocument printedPdfDocument, Context context)
{
File file = new File(context.getFilesDir(), "share.pdf");
try {
FileOutputStream outputStream = new FileOutputStream(file);
printedPdfDocument.writeTo(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
printedPdfDocument.close();
return file;
}
private static PrintedPdfDocument bitmapToPdf(Bitmap bitmap, Context context)
{
PrintAttributes printAttributes = new PrintAttributes.Builder()
.setColorMode(PrintAttributes.COLOR_MODE_COLOR)
.setMediaSize(PrintAttributes.MediaSize.ISO_A4)
.setMinMargins(PrintAttributes.Margins.NO_MARGINS)
.setResolution(new PrintAttributes.Resolution("1", "label", 300, 300))
.build();
PrintedPdfDocument printedPdfDocument = new PrintedPdfDocument(context, printAttributes);
PdfDocument.Page pdfDocumentPage = printedPdfDocument.startPage(1);
Canvas pdfCanvas = pdfDocumentPage.getCanvas();
bitmap = scaleBitmapToHeight(bitmap, pdfCanvas.getHeight());
pdfCanvas.drawBitmap(bitmap, 0f, 0f, null);
printedPdfDocument.finishPage(pdfDocumentPage);
return printedPdfDocument;
}
private static Bitmap webviewToBitmap(WebView webView) {
webView.measure(
View.MeasureSpec.makeMeasureSpec(
0,
View.MeasureSpec.UNSPECIFIED
),
View.MeasureSpec.makeMeasureSpec(
0,
View.MeasureSpec.UNSPECIFIED
)
);
int webViewWidth = webView.getMeasuredWidth();
int webViewHeight = webView.getMeasuredHeight();
webView.layout(0,0, webViewWidth, webViewHeight );
Bitmap bitmap = Bitmap.createBitmap(webViewWidth, webViewHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(bitmap, 0, bitmap.getHeight(), new Paint());
webView.draw(canvas);
return bitmap;
}
private static Bitmap scaleBitmapToHeight(Bitmap bitmap, int maxHeight) {
int height = bitmap.getHeight();
if(height > maxHeight) {
int width = bitmap.getWidth();
float scalePercentage = ((float)maxHeight) / height;
return Bitmap.createScaledBitmap(bitmap, (int) (width * scalePercentage), maxHeight, false);
}
return bitmap;
}

Bitmap Image Saved to Internal Storage is Corrupt

I want to design an app that generates a QR code and gives the user the possibility to save the generated image to their internal storage only. I successfully generate the bitmap and save it as .PNG image, but when I try to open it from the gallery it appears broken or corrupt.
Below is the code to generate the bitmap and display it on an ImageView(qrCode):
bitmap = encodeAsBitmap(value);
qrCode.setImageBitmap(bitmap);
Bitmap encodeAsBitmap(String str) throws WriterException {
BitMatrix result;
try {
result = new MultiFormatWriter().encode(str,
BarcodeFormat.QR_CODE, WIDTH, WIDTH, null);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int w = result.getWidth();
int h = result.getHeight();
int[] pixels = new int[w * h];
for (int y = 0; y < h; y++) {
int offset = y * w;
for (int x = 0; x < w; x++) {
pixels[offset + x] = result.get(x, y) ? getResources().getColor(R.color.colorBlack) :
getResources().getColor(R.color.colorWhite);
}
}
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, 500, 0, 0, w, h);
return bitmap;
}
It works perfectly up to this level. The user can then click a button in order to save this image to their device's internal storage, thanks to the below method:
public void onClickSaveCode(View view) {
String title = getResources().getString(R.string.saved_image_title_prepend) + stringDate;
String format = getResources().getString(R.string.saved_image_format);
String directory = getResources().getString(R.string.saved_image_directory);
// Method call to save image
saveImageToInternalStorage(bitmap, directory, title, format);
}
public boolean saveImageToInternalStorage(Bitmap bitmap, String directory, String title, String format) {
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File imageDirectory = contextWrapper.getDir(directory, Context.MODE_WORLD_READABLE);
File path = new File(imageDirectory, title + format);
try {
FileOutputStream fos = new FileOutputStream(path);
// Use the compress method on the Bitmap object to write image to the OutputStream
bitmap.compress(Bitmap.CompressFormat.PNG, QUALITY, fos);
fos.close();
new SingleMediaScanner(this, path);
Toast.makeText(this, getString(R.string.save_success), Toast.LENGTH_LONG).show();
return true;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, getString(R.string.save_failure), Toast.LENGTH_LONG).show();
return false;
}
}
And finally below is the MediaScannerConnection class to scan for all images saved to the device and display them in the gallery:
public class SingleMediaScanner implements MediaScannerConnectionClient {
private MediaScannerConnection mSC;
private File file;
public SingleMediaScanner(Context context, File f) {
file = f;
mSC = new MediaScannerConnection(context, this);
mSC.connect();
}
#Override
public void onMediaScannerConnected() {
mSC.scanFile(file.getAbsolutePath(), null);
}
#Override
public void onScanCompleted(String path, Uri uri) {
mSC.disconnect();
}
}
The images are saved, yet they appear in the gallery as broken files.
Any help will be greatly appreciated.
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
string filePath = System.IO.Path.Combine(path, "compressed.png");
//Bitmap bmp = ((BitmapDrawable)imgV.Drawable).Bitmap;
Bitmap b = newBitmap;
FileStream ms = new FileStream(filePath, FileMode.Create);
//FileOutputStream fos = new FileOutputStream(filePath,true);
await b.CompressAsync(Bitmap.CompressFormat.Png, 100, ms);
ms.Close();
//ByteArrayOutputStream opstream = new ByteArrayOutputStream();
//b.Compress(Bitmap.CompressFormat.Png, 100, opstream);
//byte[] bytArray = opstream.ToByteArray();
Toast.MakeText(Application.Context, "Compressed : " , ToastLength.Short).Show();
imgCompress.SetImageBitmap(b);

When saving bitmap to disk, solid paths show artifacts

[Edit: I've made a minimal project to try to narrow down what's going on. The code at the bottom still generates the same artifacts when saved]
I have an app that draws simple 2D geometry using Paths. The shapes are all solid colors, sometimes with alpha < 255, and may be decorated with lines. In the View that draws the geometry, there has never been an issue with how things get drawn. However, when I use the same code to draw to a Bitmap, and then save it as either a JPEG (with 100 quality) or PNG, there is always the same artifacting in the solid-colored areas of the output files. It's a sort of mottling that is usually associated with JPEG compression.
Screenshot of View:
Saved image:
Zoom in on artifacts:
I have tried the following
Saving to either PNG and JPEG
Turning dithering and antialiasing on and off
Increasing the DPI of the Bitmap, and also allowed the Bitmap to use its default API
Applying the matrix I use as a camera to the geometric representation, instead of applying it to the Canvas for the bitmap
Turning HW Acceleration on and off app-wide
Using a 3rd party library to save the Bitmap to a .bmp file
All yield the same artifacts, neither making it worse nor better.
public class MainActivity extends AppCompatActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = getApplicationContext();
}
// button OnClick listener
public void saveImage(View view) {
new saveBitmapToDisk().execute(false);
}
public Bitmap getBitmap() {
final int bitmapHeight = 600, bitmapWidth = 600;
Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas bitmapCanvas = new Canvas(bitmap);
float[] triangle = new float[6];
triangle[0] = bitmapWidth / 2;
triangle[1] = 0;
triangle[2] = 0;
triangle[3] = bitmapHeight / 2;
triangle[4] = bitmapWidth / 2;
triangle[5] = bitmapHeight / 2;
Path solidPath = new Path();
Paint solidPaint = new Paint();
solidPaint.setStyle(Paint.Style.FILL);
solidPath.moveTo(triangle[0], triangle[1]);
for(int i = 2; i < triangle.length; i += 2)
solidPath.lineTo(triangle[i], triangle[i+1]);
solidPath.close();
solidPaint.setColor(Color.GREEN);
bitmapCanvas.drawPath(solidPath, solidPaint);
return bitmap;
}
private class saveBitmapToDisk extends AsyncTask<Boolean, Integer, Uri> {
Boolean toShare;
#Override
protected Uri doInBackground(Boolean... shareFile) {
this.toShare = shareFile[0];
final String appName = context.getResources().getString(R.string.app_name);
final String IMAGE_SAVE_DIRECTORY = String.format("/%s/", appName);
final String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + IMAGE_SAVE_DIRECTORY;
File dir, file;
try {
dir = new File(fullPath);
if (!dir.exists())
dir.mkdirs();
OutputStream fOut;
file = new File(fullPath, String.format("%s.png", appName));
for (int suffix = 0; file.exists(); suffix++)
file = new File(fullPath, String.format("%s%03d.png", appName, suffix));
file.createNewFile();
fOut = new FileOutputStream(file);
Bitmap saveBitmap = getBitmap();
saveBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (OutOfMemoryError e) {
Log.e("MainActivity", "Out of Memory saving bitmap; bitmap is too large");
return null;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage());
return null;
}
return Uri.fromFile(file);
}
#Override
protected void onPostExecute(Uri uri) {
super.onPostExecute(uri);
Toast.makeText(context, "Image saved", Toast.LENGTH_SHORT).show();
}
}
}
I tested your program with PNG and the file has no artifacts
These artifacts are a result of JPEG compression
Edit:
The line
MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
was causing the conversion to jpeg.
The proper way to save the image is
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Here is my simplified test program that sends the generated file directly
public class Test2Activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new saveBitmapToDisk().execute();
}
public Bitmap getBitmap() {
final int bitmapHeight = 600, bitmapWidth = 600;
Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas bitmapCanvas = new Canvas(bitmap);
Paint solidPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
solidPaint.setStyle(Paint.Style.FILL);
solidPaint.setColor(Color.RED);
bitmapCanvas.drawCircle(300, 300, 200, solidPaint);
return bitmap;
}
private class saveBitmapToDisk extends AsyncTask<Void, Void, Uri> {
Boolean toShare;
#Override
protected Uri doInBackground(Void... shareFile) {
Context context = Test2Activity.this;
try {
File file = new File(context.getExternalFilesDir(null), "test.png");
FileOutputStream fOut = new FileOutputStream(file);
Bitmap saveBitmap = getBitmap();
saveBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
return Uri.fromFile(file);
} catch (OutOfMemoryError e) {
Log.e("MainActivity", "Out of Memory saving bitmap; bitmap is too large");
return null;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(Uri uri) {
Context context = Test2Activity.this;
Toast.makeText(context, "Image saved", Toast.LENGTH_SHORT).show();
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/png");
Test2Activity.this.startActivity(intent);
}
}
}
Artifacts like this are natural and unavoidable consequence of JPEG compression.
They should not crop up in PNG compression. If you are getting such artifacts when you create a PNG file, I'd wager that you are not creating a PNG stream at all, but rather a JPEG stream in a file with a PNG extension. No decent decoder relies on the file extension.
I noticed two things in your code:
1) The filename you save to is String.format("%s.jpg", appName) or String.format("%s%03d.png", appName, suffix) independent of the actual encoding.
2) The bitmap you save has its density determined by prefs.saveImageDensity().get() so it may not be the same as the actual density of the bitmap you see on the screen.
Maybe you confused yourself with 1) or perhaps 2) causes the compression-artefacts you're seeing?

Android App Creates Incomplete Images

I'm developing an app that combines two bitmaps, where one bitmap is from drawable, and the other is taken from a camera snapshot. However the pictures always end up incomplete. Half the picture is fine, but the other half is gray. Is there a way to make sure that the file is completed before the app moves on with the code? Below is the code that works with writing and saving the file. Thanks
Combine.java
protected void createPostcard(byte[] data, File pictureFile, CameraActivity app, Button shareButton,
Button newButton) {
try {
Bitmap photo = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap splash = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(app.getResources(),
R.drawable.wishsplash), photo.getWidth(), photo.getHeight(), false);
Bitmap postcard = Bitmap.createBitmap(photo.getWidth(), photo.getHeight(), photo.getConfig());
Canvas canvas = new Canvas(postcard);
canvas.drawBitmap(photo, new Matrix(), null);
canvas.drawBitmap(splash, 0, 0, null);
savePostcard(postcard, pictureFile, app, shareButton, newButton);
} catch (Exception e) {
}//end catch
}//end createPostcard
/**
* Saves the postcard
*/
private void savePostcard(Bitmap postcard, File pictureFile, CameraActivity app, Button shareButton,
Button newButton) {
BitmapDrawable mBitmapDrawable = new BitmapDrawable(postcard);
Bitmap mNewSaving = mBitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mNewSaving.compress(CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
save(byteArray, pictureFile, app);
shareButton.setBackgroundResource(R.drawable.sharebutton);
newButton.setBackgroundResource(R.drawable.newbutton);
shareButton.setEnabled(true);
newButton.setEnabled(true);
}//end savePostcard
/**
* Check if external is available. If not, postcard will be saved in internal.
* #retun
*/
private void save(byte[] data, File pictureFile, CameraActivity app) {
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
FileOutputStream fos = new FileOutputStream(pictureFile);
imageUri = Uri.fromFile(pictureFile);
fos.write(data);
imageFile = pictureFile;
fos.close();
app.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
} else {
File cache = app.getCacheDir();
File internalPic = new File(cache, pictureFile.getName());
FileOutputStream fos = new FileOutputStream(internalPic);
imageUri = Uri.fromFile(internalPic);
imageFile = internalPic;
fos.write(data);
fos.close();
}//end else
} catch (FileNotFoundException e) {
System.out.println("FILENOTFOUND");
} catch (IOException e) {
System.out.println("IOEXCEPTION");
}//end catch
}//end getStorage
try this code
public Bitmap PutoverBmp(Bitmap all, Bitmap scaledBorder) {
Paint paint = new Paint();
final int width = bmp.getWidth(); // bmp is your main Bitmap
final int height = bmp.getHeight();
patt = Bitmap.createScaledBitmap(bmp, width, height, true);
Bitmap mutableBitmap = patt.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
scaledBorder = Bitmap.createScaledBitmap(border, width, height, true);
paint.setAlpha(100);
canvas.drawBitmap(scaledBorder, 0, 0, paint);
return mutableBitmap;
}
simply call this Bitmap combine = (bmp , yourOtherBitmap);

Categories

Resources