can somebody help me with this problem?
I want that images are displayed at the beginning of the gallery.
What have i to change in my code?
OutputStream fOut = null;
try {
String path = getFilesDir().getPath();
File file = new File(path, "LT-IMG-"+ts+".jpg");
fOut = new FileOutputStream(file);
Bitmap bitmap = ((BitmapDrawable)photoView.getDrawable()).getBitmap();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (IOException ex) {
ex.printStackTrace();
}
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
The former code will add the image at the end of the gallery. If you want to modify the date so it appears at the beginning or any other metadata, see the code below (Cortesy of S-K, samkirton):
https://gist.github.com/samkirton/0242ba81d7ca00b475b9
/**
* Android internals have been modified to store images in the media
folder with * the correct date meta data * #author samuelkirton*/
public class CapturePhotoUtils {
/**
* A copy of the Android internals insertImage method, this method populates the
* meta data with DATE_ADDED and DATE_TAKEN. This fixes a common problem where media
* that is inserted manually gets saved at the end of the gallery (because date is not populated).
* #see android.provider.MediaStore.Images.Media#insertImage(ContentResolver, Bitmap, String, String)
*/
public static final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description) {
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DISPLAY_NAME, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F,Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}
/**
* A copy of the Android internals StoreThumbnail method, it used with the insertImage to
* populate the android.provider.MediaStore.Images.Media#insertImage with all the correct
* meta data. The StoreThumbnail method is private so it must be duplicated here.
* #see android.provider.MediaStore.Images.Media (StoreThumbnail private method)
*/
private static final Bitmap storeThumbnail(
ContentResolver cr,
Bitmap source,
long id,
float width,
float height,
int kind) {
// create the matrix to scale it
Matrix matrix = new Matrix();
float scaleX = width / source.getWidth();
float scaleY = height / source.getHeight();
matrix.setScale(scaleX, scaleY);
Bitmap thumb = Bitmap.createBitmap(source, 0, 0,
source.getWidth(),
source.getHeight(), matrix,
true
);
ContentValues values = new ContentValues(4);
values.put(Images.Thumbnails.KIND,kind);
values.put(Images.Thumbnails.IMAGE_ID,(int)id);
values.put(Images.Thumbnails.HEIGHT,thumb.getHeight());
values.put(Images.Thumbnails.WIDTH,thumb.getWidth());
Uri url = cr.insert(Images.Thumbnails.EXTERNAL_CONTENT_URI, values);
try {
OutputStream thumbOut = cr.openOutputStream(url);
thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut);
thumbOut.close();
return thumb;
} catch (FileNotFoundException ex) {
return null;
} catch (IOException ex) {
return null;
}
}
}
Related
I am trying to take multiple images but the ImageAvailabeListener function is not moving forward. I guess it is waiting for next image. I tried aquireNextImage() but it is also not working.
I'm taking images while MediaProjection.
private class ImageAvailableListener implements ImageReader.OnImageAvailableListener {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
FileOutputStream fos = null;
bitmap = null;
try {
image = mImageReader.acquireLatestImage();
if (image != null) {
Log.d("servicecheck", "not null image" + image);
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[counter].getBuffer();
int pixelStride = planes[counter].getPixelStride();
int rowStride = planes[counter].getRowStride();
counter++;
int rowPadding = rowStride - pixelStride * mWidth;
// create bitmap
bitmap = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
// fix the extra width from Image
Bitmap croppedBitmap;
try {
croppedBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight);
} catch (OutOfMemoryError e) {
croppedBitmap = bitmap;
}
if (croppedBitmap != bitmap) {
bitmap.recycle();
}
// write bitmap to a file
storeDirectory = new File(mStoreDir);
storeDirectory.mkdir();
fos = new FileOutputStream(storeDirectory.getAbsolutePath() + "/myscreen_" + Calendar.getInstance().getTime() + ".png");
croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
//IMAGES_PRODUCED++;
fos.flush();
fos.close();
stopProjection();
stopSelf();
scanFile(getApplicationContext(), Uri.fromFile(storeDirectory));
} else {
Log.d("servicecheck", "null image" + image);
}
} catch (Exception e) {
if (bitmap != null) {
bitmap.recycle();
}
e.printStackTrace();
}
}
}
//In the below function I have created set maxImages to 5(more than 1)
#SuppressLint("WrongConstant")
private void createVirtualDisplay() {
mImageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 20);
mVirtualDisplay = mMediaProjection.createVirtualDisplay(SCREENCAP_NAME, mWidth, mHeight,
mDensity, getVirtualDisplayFlags(), mImageReader.getSurface(), null, null);
mImageReader.setOnImageAvailableListener(new ImageAvailableListener(), null);
}
I have String with Html format. My Html can contains any tags like image , video , ...
I can now handle image and text like this correctly :
I have a textView in my xml:
TextView textView = new TextView(DetailActivity.this);
textView.setText(Html.fromHtml(content, new Html.ImageGetter() {
#Override
public Drawable getDrawable(String source) {
try {
URI uri = new URI(source);
URL videoUrl = uri.toURL();
File tempFile = new File(videoUrl.getFile());
filename = tempFile.getName();
} catch (Exception e) {
}
Drawable drawable = null;
ContextWrapper cw1 = new ContextWrapper(DetailActivity.this);
File directory1 = cw1.getDir("multiImage", Context.MODE_PRIVATE);
final File myImageFile1 = new File(directory1, filename);
File f = new File(myImageFile1.getAbsolutePath());
Log.i("multiImage", filename);
final ImageView imageView = new ImageView(DetailActivity.this);
if (f.exists()) {
drawable = Drawable.createFromPath(myImageFile1.getAbsolutePath());
//drawable.setBounds(0, 0, drawable.getIntrinsicHeight(), drawable.getIntrinsicWidth());
int imgH = drawable.getIntrinsicHeight();
int imgW = drawable.getIntrinsicWidth();
int padding = 20;
int realWidth = ScreenW - (2 * padding);
int realHeight = imgH * realWidth / imgW;
drawable.setBounds(padding, 0, realWidth, realHeight);
} else {
Picasso.with(DetailActivity.this)
.load(source)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
BitmapDrawable draw = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = draw.getBitmap();
FileOutputStream outStream = null;
File outFile = new File(myImageFile1.getAbsolutePath());
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onError() {
}
});
URL sourceURL;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
sourceURL = new URL(source);
URLConnection urlConnection = sourceURL.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
BufferedInputStream bufferedInputStream =
new BufferedInputStream(inputStream);
Bitmap bm = BitmapFactory.decodeStream(bufferedInputStream);
// convert Bitmap to Drawable
drawable = new BitmapDrawable(getResources(), bm);
int imgH = drawable.getIntrinsicHeight();
int imgW = drawable.getIntrinsicWidth();
int padding = 20;
int realWidth = ScreenW - (2 * padding);
int realHeight = imgH * realWidth / imgW;
drawable.setBounds(padding, 0, realWidth, realHeight);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return drawable;
}
}, new UlTagHandler()));
But I can not show video using above code.
I want to split my string --> from the first until the video tag and then video tag at the end of video tag and the rest of string .
I am trying to convert a pdf stored in my assets folder into bitmap using PdfViewer.jar.
This is my code:
public static Bitmap renderToBitmap(InputStream inStream) {
Bitmap bitmap = null;
try {
byte[] bArray = IOUtils.toByteArray(inStream);
ByteBuffer buf = ByteBuffer.wrap(bArray);
PDFPage mPdfPage = new PDFFile(buf).getPage(0, true);
float width = mPdfPage.getWidth();
float height = mPdfPage.getHeight();
bitmap = mPdfPage.getImage((int) (width), (int) (height), null);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inStream.close();
} catch (IOException e) {
// do nothing because the stream has already been closed
}
}
return bitmap;
}
This code is doing what I need. But the resulting bitmap quality is very poor.
How can I increase the quality of bitmap created ?
I am trying to use html 5 image upload, but the problem I'm facing is when I try to decode the 64 encoded image it throws some error, here is my code:
public String decodeToImage() throws IOException {
destPath = "/home/user/deskTop";
byte[] imageByte;
String imageData = request.getParameter("img");
String base64Image = imageData.split(",")[1];
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(base64Image);
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageByte));
File outputfile = new File(destPath, "11111.png");
try
{
ImageIO.write(img, "jpg", outputfile);
}
catch(Exception e)
{
e.printStackTrace();
}
return SUCCESS;
}
When I am trying to write the image in File from Buffer Image it throws this error:
"Invalid argument to native writeImage"
When I asked the error elsewhere, someone said that it may be because of using open-jdk.
Here is my JavaScriot:
crop = function() {
//Find the part of the image that is inside the crop box
var crop_canvas,
left = $('.imgOverlay').offset().left - $container.offset().left,
top = $('.imgOverlay').offset().top - $container.offset().top,
width = $('.imgOverlay').width(),
height = $('.imgOverlay').height();
crop_canvas = document.createElement('canvas');
crop_canvas.width = width;
crop_canvas.height = height;
crop_canvas.getContext('2d').drawImage(image_target, left, top, width, height, 0, 0, width, height);
var onSuccesOfUpload = function(data) {
alert();
};
var onErrorOfUpload = function(data) {
alert();
};
var data = function(data) {
alert();
};
var data = {
'img': crop_canvas.toDataURL("image/png")
};
callToDB('/canvasImageUpload.action', 'POST', data, onSuccesOfUpload, onErrorOfUpload);
}
I'm developing an android app using Google Maps API V2 and i have to use offline tiles, i have all tiles (from open street maps in png format) of my entire city in my SD Card.
I already tried to use TileProvider Interface but didn't work.
How can i do that ?
Thanks in advance.
I modified somethings and it worked. Here is the code:
CustomMapTileProvider.java
public class CustomMapTileProvider implements TileProvider {
private static final int TILE_WIDTH = 256;
private static final int TILE_HEIGHT = 256;
private static final int BUFFER_SIZE = 16 * 1024;
Override
public Tile getTile(int x, int y, int zoom) {
byte[] image = readTileImage(x, y, zoom);
return image == null ? null : new Tile(TILE_WIDTH, TILE_HEIGHT, image);
}
private byte[] readTileImage(int x, int y, int zoom) {
FileInputStream in = null;
ByteArrayOutputStream buffer = null;
try { in = new FileInputStream(getTileFile(x, y, zoom));
buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[BUFFER_SIZE];
while ((nRead = in .read(data, 0, BUFFER_SIZE)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
} finally {
if ( in != null)
try { in .close();
} catch (Exception ignored) {}
if (buffer != null)
try {
buffer.close();
} catch (Exception ignored) {}
}
}
private File getTileFile(int x, int y, int zoom) {
File sdcard = Environment.getExternalStorageDirectory();
String tileFile = "/TILES_FOLDER/" + zoom + '/' + x + '/' + y + ".png";
File file = new File(sdcard, tileFile);
return file;
}
}
Add TileOverlay to your GoogleMap instance
...
map.setMapType(GoogleMap.MAP_TYPE_NONE);
TileOverlayOptions tileOverlay = new TileOverlayOptions();
tileOverlay.tileProvider(new CustomMapTileProvider());
map.addTileOverlay(tileOverlay).setZIndex(0);
...