How to get Alpha of a Bitmap? - android

I have two problems.
First I am changing the alpha of a Bitmap and saving it to an ImageView but whenever I am getting the Bitmap from the ImageView it is different to how it looks in the ImageView, the RGB values are Changed.
Second, I am wondering how to get alpha of a bitmap.
imageview=(ImageView)findViewById(R.id.image);
public Bitmap ColorDodgeBlend(Bitmap source, Bitmap layer,int alpha) {
Bitmap base = source.copy(Config.ARGB_8888, true);
Bitmap blend = layer.copy(Config.ARGB_8888, false);
IntBuffer buffBase = IntBuffer.allocate(base.getWidth() * base.getHeight());
base.copyPixelsToBuffer(buffBase);
buffBase.rewind();
IntBuffer buffBlend = IntBuffer.allocate(blend.getWidth() * blend.getHeight());
blend.copyPixelsToBuffer(buffBlend);
buffBlend.rewind();
IntBuffer buffOut = IntBuffer.allocate(base.getWidth() * base.getHeight());
buffOut.rewind();
while (buffOut.position() < buffOut.limit()) {
int filterInt = buffBlend.get();
int srcInt = buffBase.get();
int redValueFilter = Color.red(filterInt);
int greenValueFilter = Color.green(filterInt);
int blueValueFilter = Color.blue(filterInt);
int redValueSrc = Color.red(srcInt);
int greenValueSrc = Color.green(srcInt);
int blueValueSrc = Color.blue(srcInt);
int redValueFinal = colordodge(redValueFilter, redValueSrc);
int greenValueFinal = colordodge(greenValueFilter, greenValueSrc);
int blueValueFinal = colordodge(blueValueFilter, blueValueSrc);
int pixel = Color.argb(alpha, redValueFinal, greenValueFinal, blueValueFinal);
buffOut.put(pixel);
}
buffOut.rewind();
base.copyPixelsFromBuffer(buffOut);
blend.recycle();
return base;
};
bmp=ColorDodgeBlend(Bitmap source, Bitmap layer,alpha); imageview.setImageBitmap(bmp);
But when I try to save bitmap from ImageView, the rgb of saved bitmap is different to how it appears in the ImageView, changing alpha changes the value of rgb.
public Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b
}
bitmap b=loadBitmapFromView(imageview);
saveBitmap(b);
private void saveBitmap(Bitmap bmp) {
try {
File f = new File(Environment.getExternalStorageDirectory()
+ "/Pictures/SketchPhoto/");
f.mkdirs();
Date d = new Date();
CharSequence s = DateFormat
.format("MM-dd-yy hh-mm-ss", d.getTime());
fileName = s.toString() + ".jpeg";
String fullf = f + "/" + fileName;
FileOutputStream fos = new FileOutputStream(fullf);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
Toast.makeText(getApplicationContext(), "Sketch Saved", 100).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
I have done some research and found that it only happens when that value of alpha is smaller than 255.

Related

Printooth Error doesn't print image Attempt to invoke virtual method on a null object reference

I'm trying to print my Scroll View layout to my bluetooth printer using Printooth. I try to convert the layout to Bitmap using getBitmapFromView() Method and print using this
printables.add(new ImagePrintable.Builder(b).build());
printing.print(printables);
But when i try to print it, the app doesnt do anything and have this error,
Can anybody help me solve this ?:
Attempt to invoke virtual method 'void com.mazenrashed.printooth.utilities.Printing.print(java.util.ArrayList)' on a null object reference
This is the code:
private void takeScreenShot() {
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ScreenShot/");
if (!folder.exists()) {
boolean success = folder.mkdir();
}
path = folder.getAbsolutePath();
path = path + "/" + file_name + System.currentTimeMillis() + ".pdf";
// List<Integer> hights = new ArrayList<>();
View u = findViewById(R.id.scroll);
NestedScrollView z = (NestedScrollView) findViewById(R.id.scroll);
totalHeight = z.getChildAt(0).getHeight();
totalWidth = z.getChildAt(0).getWidth();
Log.e("totalHeight--", "" + totalHeight);
Log.e("totalWidth--", "" + totalWidth);
//Save bitmap
String extr = Environment.getExternalStorageDirectory() + "/ScreenShot/";
File file = new File(extr);
if (!file.exists())
file.mkdir();
fileName = file_name + ".jpg";
myPath = new File(extr, fileName);
imagesUri = myPath.getPath();
FileOutputStream fos = null;
b = getBitmapFromView(u, totalHeight, totalWidth);
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// createPdf();
final ArrayList<Printable> printables = new ArrayList<>();
printables.add(new ImagePrintable.Builder(b).build());
printing.print(printables);
}
public Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {
Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth, totalHeight, 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);
toGrayscale(returnedBitmap);
return returnedBitmap;
}
public static Bitmap toGrayscale(Bitmap srcImage) {
Bitmap bmpGrayscale = Bitmap.createBitmap(srcImage.getWidth(),
srcImage.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
paint.setColorFilter(new ColorMatrixColorFilter(cm));
canvas.drawBitmap(srcImage, 0, 0, paint);
return bmpGrayscale;
}
this is my Scroll view layout that i want to print :
Change
printing.print(printables);
to
Printooth.INSTANCE.printer().print(printables);

How to take picture with camera using ARCore

ARCore camera doesn't seem to support takePicture.
https://developers.google.com/ar/reference/java/com/google/ar/core/Camera
Anyone know how I can take pictures with ARCore?
I am assuming you mean a picture of what the camera is seeing and the AR objects. At a high level you need to get permission to write to external storage to save the picture, copy the frame from OpenGL and then save it as a png (for example). Here are the specifics:
Add the WRITE_EXTERNAL_STORAGE permission to the AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Then change CameraPermissionHelper to iterate over both the CAMERA and WRITE_EXTERNAL_STORAGE permissions to make sure they are granted
private static final String REQUIRED_PERMISSIONS[] = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
/**
* Check to see we have the necessary permissions for this app.
*/
public static boolean hasCameraPermission(Activity activity) {
for (String p : REQUIRED_PERMISSIONS) {
if (ContextCompat.checkSelfPermission(activity, p) !=
PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
/**
* Check to see we have the necessary permissions for this app,
* and ask for them if we don't.
*/
public static void requestCameraPermission(Activity activity) {
ActivityCompat.requestPermissions(activity, REQUIRED_PERMISSIONS,
CAMERA_PERMISSION_CODE);
}
/**
* Check to see if we need to show the rationale for this permission.
*/
public static boolean shouldShowRequestPermissionRationale(Activity activity) {
for (String p : REQUIRED_PERMISSIONS) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, p)) {
return true;
}
}
return false;
}
Next, add a couple fields to HelloARActivity to keep track of the dimensions of the frame and boolean to indicate when to save the picture.
private int mWidth;
private int mHeight;
private boolean capturePicture = false;
Set the width and height in onSurfaceChanged()
public void onSurfaceChanged(GL10 gl, int width, int height) {
mDisplayRotationHelper.onSurfaceChanged(width, height);
GLES20.glViewport(0, 0, width, height);
mWidth = width;
mHeight = height;
}
At the bottom of onDrawFrame(), add a check for the capture flag. This should be done after all the other drawing happens.
if (capturePicture) {
capturePicture = false;
SavePicture();
}
Then add the onClick method for a button to take the picture, and the actual code to save the image:
public void onSavePicture(View view) {
// Here just a set a flag so we can copy
// the image from the onDrawFrame() method.
// This is required for OpenGL so we are on the rendering thread.
this.capturePicture = true;
}
/**
* Call from the GLThread to save a picture of the current frame.
*/
public void SavePicture() throws IOException {
int pixelData[] = new int[mWidth * mHeight];
// Read the pixels from the current GL frame.
IntBuffer buf = IntBuffer.wrap(pixelData);
buf.position(0);
GLES20.glReadPixels(0, 0, mWidth, mHeight,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buf);
// Create a file in the Pictures/HelloAR album.
final File out = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES) + "/HelloAR", "Img" +
Long.toHexString(System.currentTimeMillis()) + ".png");
// Make sure the directory exists
if (!out.getParentFile().exists()) {
out.getParentFile().mkdirs();
}
// Convert the pixel data from RGBA to what Android wants, ARGB.
int bitmapData[] = new int[pixelData.length];
for (int i = 0; i < mHeight; i++) {
for (int j = 0; j < mWidth; j++) {
int p = pixelData[i * mWidth + j];
int b = (p & 0x00ff0000) >> 16;
int r = (p & 0x000000ff) << 16;
int ga = p & 0xff00ff00;
bitmapData[(mHeight - i - 1) * mWidth + j] = ga | r | b;
}
}
// Create a bitmap.
Bitmap bmp = Bitmap.createBitmap(bitmapData,
mWidth, mHeight, Bitmap.Config.ARGB_8888);
// Write it to disk.
FileOutputStream fos = new FileOutputStream(out);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
runOnUiThread(new Runnable() {
#Override
public void run() {
showSnackbarMessage("Wrote " + out.getName(), false);
}
});
}
Last step is to add the button to the end of activity_main.xml layout
<Button
android:id="#+id/fboRecord_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/surfaceview"
android:layout_alignTop="#+id/surfaceview"
android:onClick="onSavePicture"
android:text="Snap"
tools:ignore="OnClick"/>
Acquiring the image buffer
In the latest ARCore SDK, we get access to the image buffer via public class Frame. Below is the sample code which gives us access to the image buffer.
private void onSceneUpdate(FrameTime frameTime) {
try {
Frame currentFrame = sceneView.getArFrame();
Image currentImage = currentFrame.acquireCameraImage();
int imageFormat = currentImage.getFormat();
if (imageFormat == ImageFormat.YUV_420_888) {
Log.d("ImageFormat", "Image format is YUV_420_888");
}
}
onSceneUpdate() will be called for every update if you register it to setOnUpdateListener() callback. Image will be in YUV_420_888 format, but it will have full Field of view of native high resolution camera.
Also do not forget to close resources of received image by calling currentImage.close(). Otherwise you will receive a ResourceExhaustedException on the next run of onSceneUpdate.
Writing the acquired image buffer to a file
Following implementation converts YUV buffer to compressed JPEG byte array
private static byte[] NV21toJPEG(byte[] nv21, int width, int height) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
YuvImage yuv = new YuvImage(nv21, ImageFormat.NV21, width, height, null);
yuv.compressToJpeg(new Rect(0, 0, width, height), 100, out);
return out.toByteArray();
}
public static void WriteImageInformation(Image image, String path) {
byte[] data = null;
data = NV21toJPEG(YUV_420_888toNV21(image),
image.getWidth(), image.getHeight());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
bos.write(data);
bos.flush();
bos.close();
}
private static byte[] YUV_420_888toNV21(Image image) {
byte[] nv21;
ByteBuffer yBuffer = image.getPlanes()[0].getBuffer();
ByteBuffer uBuffer = image.getPlanes()[1].getBuffer();
ByteBuffer vBuffer = image.getPlanes()[2].getBuffer();
int ySize = yBuffer.remaining();
int uSize = uBuffer.remaining();
int vSize = vBuffer.remaining();
nv21 = new byte[ySize + uSize + vSize];
//U and V are swapped
yBuffer.get(nv21, 0, ySize);
vBuffer.get(nv21, ySize, vSize);
uBuffer.get(nv21, ySize + vSize, uSize);
return nv21;
}
Sorry for answering late.You can use code to click picture in ARCore:
private String generateFilename() {
String date =
new SimpleDateFormat("yyyyMMddHHmmss", java.util.Locale.getDefault()).format(new Date());
return Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES) + File.separator + "Sceneform/" + date + "_screenshot.jpg";
}
private void saveBitmapToDisk(Bitmap bitmap, String filename) throws IOException {
File out = new File(filename);
if (!out.getParentFile().exists()) {
out.getParentFile().mkdirs();
}
try (FileOutputStream outputStream = new FileOutputStream(filename);
ByteArrayOutputStream outputData = new ByteArrayOutputStream()) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputData);
outputData.writeTo(outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException ex) {
throw new IOException("Failed to save bitmap to disk", ex);
}
}
private void takePhoto() {
final String filename = generateFilename();
/*ArSceneView view = fragment.getArSceneView();*/
mSurfaceView = findViewById(R.id.surfaceview);
// Create a bitmap the size of the scene view.
final Bitmap bitmap = Bitmap.createBitmap(mSurfaceView.getWidth(), mSurfaceView.getHeight(),
Bitmap.Config.ARGB_8888);
// Create a handler thread to offload the processing of the image.
final HandlerThread handlerThread = new HandlerThread("PixelCopier");
handlerThread.start();
// Make the request to copy.
PixelCopy.request(mSurfaceView, bitmap, (copyResult) -> {
if (copyResult == PixelCopy.SUCCESS) {
try {
saveBitmapToDisk(bitmap, filename);
} catch (IOException e) {
Toast toast = Toast.makeText(DrawAR.this, e.toString(),
Toast.LENGTH_LONG);
toast.show();
return;
}
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
"Photo saved", Snackbar.LENGTH_LONG);
snackbar.setAction("Open in Photos", v -> {
File photoFile = new File(filename);
Uri photoURI = FileProvider.getUriForFile(DrawAR.this,
DrawAR.this.getPackageName() + ".ar.codelab.name.provider",
photoFile);
Intent intent = new Intent(Intent.ACTION_VIEW, photoURI);
intent.setDataAndType(photoURI, "image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
});
snackbar.show();
} else {
Log.d("DrawAR", "Failed to copyPixels: " + copyResult);
Toast toast = Toast.makeText(DrawAR.this,
"Failed to copyPixels: " + copyResult, Toast.LENGTH_LONG);
toast.show();
}
handlerThread.quitSafely();
}, new Handler(handlerThread.getLooper()));
}

Add plain text to picture taken from camera intent

I have application which uses camera intent and saves picture taken into specific folder. Now i am missing one more functionality and that is that after picture is taken i should add plain text (timestamp, few more infos on picture lower/upper border) and save it.
How to achieve this? My code is below
public void takePicture( View view)
{
Intent intentCamera = new Intent();
intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
File photofile = null;
try{
photofile=createImageFile();
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photofile));
startActivityForResult(intentCamera, ActivityStartamera);
//Toast.makeText(this,Uri.fromFile(photofile).toString(), Toast.LENGTH_LONG).show();
}
catch (IOException e)
{
e.printStackTrace();
Toast.makeText(this, "Error happened", Toast.LENGTH_LONG).show();
imageFileName="";
}
}
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
if(requestCode == ActivityStartamera && resultCode == RESULT_OK)
{
//
//here i should add plain text to taken picture
//
Toast.makeText(this, "Picture taken", Toast.LENGTH_LONG).show();
}
else{
image.delete();
}
}
File createImageFile () throws IOException{
String timeStamp = new SimpleDateFormat("MMyyyydd_HHmmss").format(new Date());
imageFileName = "picture_"+timeStamp;
storage = Environment.getExternalStoragePublicDirectory("PicturesForApp");
if (!storage.exists())
{
Toast.makeText(this, "Folder made for pictures", Toast.LENGTH_LONG).show();
storage.mkdirs();
}
image = new File(storage + "/" +imageFileName +".jpg");
return image;
}
I have tried something like this but was unsucesfull.
Please use this method I am sure it will help you.
public Bitmap addTextToImage(Bitmap src, String textToAddOnImage, int x, int y, int color, int alpha, int size, boolean underline) {
int w = src.getWidth();
int h = src.getHeight();
Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Paint paint = new Paint();
paint.setColor(color);
paint.setAlpha(alpha);
paint.setTextSize(size);
paint.setAntiAlias(true);
paint.setUnderlineText(underline);
canvas.drawText(textToAddOnImage, x, y, paint);
return result;
}
Call this method like this
// use this bitmap to show in imageView and you can also save the bitmap.
Bitmap bmp = addTextToImage(srcBitmap, "Mustanser Iqbal", 200, 200, Color.GREEN, 80, 24, false);
File f = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + fileName + ".png");
FileOutputStream fos = new FileOutputStream(f);
bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);

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

Why Bitmap to Base64 String showing black background on webview in android?

I am using a code that combine to images into 1 by using canvas . I show that image to ImageView it looks fine. But when I try to show that into WebView it show background black to right that image. I try to change the background color in HTML but it not change color. or make transparent. Can anyone help? Result is here The above image is in ImageView and below is in WebView.
public class MyBimapTest extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView img1 = (ImageView) findViewById(R.id.ImageView01);
img1.setVisibility(View.INVISIBLE);
Drawable dra1 = img1.getDrawable();
Bitmap map1 = ((BitmapDrawable) dra1).getBitmap();
ImageView img2 = (ImageView) findViewById(R.id.ImageView02);
img2.setVisibility(View.INVISIBLE);
Drawable dra2 = img2.getDrawable();
Bitmap map2 = ((BitmapDrawable) dra2).getBitmap();
// ***
ByteArrayOutputStream baos = new ByteArrayOutputStream();
map1.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String abc = Base64.encodeBytes(b);
byte[] byt = null;
try {
byt = Base64.decode(abc);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
map1 = BitmapFactory.decodeByteArray(byt, 0, byt.length);
// ***
Bitmap map = combineImages(map1, map2);
ByteArrayOutputStream bbb = new ByteArrayOutputStream();
map.compress(Bitmap.CompressFormat.JPEG, 100, bbb);
byte[] bit = bbb.toByteArray();
String imgToString = Base64.encodeBytes(bit);
String imgTag = "<img src='data:image/jpg;base64," + imgToString
+ "' align='left' bgcolor='ff0000'/>";
WebView webView = (WebView) findViewById(R.id.storyView);
webView.loadData(imgTag, "text/html", "utf-8");
Drawable end = new BitmapDrawable(map);
ImageView img3 = (ImageView) findViewById(R.id.ImageView03);
img3.setImageBitmap(map);
}
public Bitmap combineImages(Bitmap c, Bitmap s) {
Bitmap cs = null;
int width, height = 0;
width = c.getWidth() + (s.getWidth() / 2);
height = c.getHeight() + (s.getHeight() / 2);
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, c.getWidth() - (s.getWidth() / 2), c
.getHeight()
- (s.getHeight() / 2), null);
return cs;
}
}
The JPEG format does not support alpha transparency, which is why the transparent background becomes black when you convert your original image to JPEG.
Use the PNG format instead:
map1.compress(Bitmap.CompressFormat.PNG, 100, baos);
and
String imgTag = "<img src='data:image/png;base64," + imgToString
+ "' align='left' bgcolor='ff0000'/>";

Categories

Resources