Android Google Maps V2 - Sd card as Tile Provider - java

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

Related

In Android how can I take multiple images through ImageReader class

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

How to split Html String Based on Html tag

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 .

Get raw bytes from QR Code with zxing lib (or convert from BitMatrix)

I need to get byte[] array from a QR Code encoded into a BitMatrix. Here's my code:
// imports
import com.google.zxing.BarcodeFormat;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.DecoderResult;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.datamatrix.decoder.Decoder;
The function to generate QR Code:
public byte[] createQRCode() {
String qrCodeData = "Hello world";
String charset = "UTF-8";
BitMatrix matrix = null;
Writer writer = new QRCodeWriter();
try {
matrix = writer.encode(new String(qrCodeData.getBytes(charset), charset), BarcodeFormat.QR_CODE, qrCodeheight, qrCodewidth);
} catch (UnsupportedEncodingException e) {
return;
}
catch (WriterException e) {
return;
}
DecoderResult decoderResult = null;
try {
decoderResult = new Decoder().decode(matrix);
} catch (ChecksumException e) {
return;
} catch (FormatException e) {
// Always this exception is throwed
}
byte[] cmd = decoderResult.getRawBytes();`
return cmd;
}
Always the execution stop on FormatException, even the parameter on Decode().decode() requested is BitMatrix.
Someone can tell me what's wrong or show me other way to get the QR Code byte array?
I found the solution using a library to decode Bitmap:
https://github.com/imrankst1221/Thermal-Printer-in-Android
Function to encode String into QR Code Bitmap:
public Bitmap encodeToQrCode(String text, int width, int height){
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = null;
try {
matrix = writer.encode(text, BarcodeFormat.QR_CODE, width, height);
} catch (WriterException ex) {
//
}
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++){
for (int y = 0; y < height; y++){
bmp.setPixel(x, y, matrix.get(x,y) ? Color.BLACK : Color.WHITE);
}
}
return bmp;
}
Then I decode bitmap to bytes using Utils from the found library:
try {
Bitmap bmp = encodeToQrCode("Hello world", 200, 200);
if (bmp != null ) {
byte[] command = Utils.decodeBitmap(bmp);
BluetoothPrintDriver.BT_Write(command);
} else {
Log.e("Print Photo error", "file not found");
}
} catch (Exception e) {
e.printStackTrace();
Log.e("PrintTools", "file not found");
}

Show Images from URL in blackberry

I used following code to preview an image from an url.
Bitmap bannerImage=Bitmap.getBitmapResource("http://www.asianmirror.lk/english/images/stories/demo/hot_news/top_news/sanga1_latest.jpg");
BitmapField banner=new BitmapField(bannerImage);
add(banner);
But the image doesn't preview in the UI. Is there is special way to preview images from a url in blackberry.(I means, shall I put the Image in to a temporary Array to preview the Image?) Thank you
try this -
URLBitmapField wmf= new util.URLBitmapField("http://www.asianmirror.lk/english/images/stories/demo/hot_news/top_news/sanga1_latest.jpg")
add(wmf);
//URLBitmapField class is given below-
public class URLBitmapField extends BitmapField implements URLDataCallback {
EncodedImage result=null ;
public static Bitmap myImage;
public static EncodedImage _encoded_img=null ;
int _imgWidth = 140;
int _imgHeight = 140;
int _imgMargin = 10;
public URLBitmapField(String url) {
try {
http_image_data_extrator.getWebData(url, this);
}
catch (Exception e) {}
}
public Bitmap getBitmap() {
if (_encoded_img == null) return null;
return _encoded_img.getBitmap();
}
public void callback(final String data) {
if (data.startsWith("Exception")) return;
try {
byte[] dataArray = data.getBytes();
//bitmap = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length);//no scale
_encoded_img = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length); // with scale
_encoded_img = sizeImage(_encoded_img, _imgWidth, _imgHeight);
constants.image=_encoded_img;
//myImage=cropImage(_encoded_img.getBitmap());
setImage(_encoded_img);
UiApplication.getUiApplication().getActiveScreen().invalidate();
}
catch (final Exception e){}
}
public EncodedImage sizeImage(EncodedImage image, int width, int height) {
int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
int currentHeightFixed32 = Fixed32.toFP(image.getHeight());
int requiredWidthFixed32 = Fixed32.toFP(width);
int requiredHeightFixed32 = Fixed32.toFP(height);
int scaleXFixed32 = Fixed32.div(currentWidthFixed32,
requiredWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32,
requiredHeightFixed32);
result = image.scaleImage32(scaleXFixed32, scaleYFixed32);
return result;
}
public class http_image_data_extrator {
static String url_="";
static StringBuffer rawResponse=null;
//static String result = null;
public static void getWebData(String url, final URLDataCallback callback) throws IOException {
//url_=url;
HttpConnection connection = null;
InputStream inputStream = null;
try {
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo
.areWAFsSupported(RadioInfo.WAF_WLAN)) {
url += ";interface=wifi";
}
connection = (HttpConnection) Connector.open(url, Connector.READ, true);
String location=connection.getHeaderField("location");
if(location!=null){
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo
.areWAFsSupported(RadioInfo.WAF_WLAN)) {
location += ";interface=wifi";
}
connection = (HttpConnection) Connector.open(location, Connector.READ, true);
}else{
connection = (HttpConnection) Connector.open(url, Connector.READ, true);
}
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK){
throw new IOException("HTTP response code: "+ responseCode);
}
final String result = rawResponse.toString();
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run(){
callback.callback(result);
}
});
}
catch (final Exception ex) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
callback.callback("Exception (" + ex.getClass() + "): " + ex.getMessage());
}
});
}
}
}
public interface URLDataCallback {
public void callback(String data);
}

Validating image dimensions in Wicket

im developing a webbapp wich receives image resources from users, but i want to validate these image to be uploaded to have specific dimensions like 600X800 etc.
I am trying to fin answers but im running out of options :).
It would be great if someone has done this before.
Thanks your help will be apreciated
Try
BufferedImage bi = ImageIO.read (file);
bi.getWidth();//width
bi.getHeight ();//height
Finally i did find the way to do it: we first get the file that its going to be uploaded, then i use a created class wich i found here on stack overflow, to find width and height of dimesions, i just play with if's then, heres the code, hope helps someone!!
public class AddPromo extends WebPage {
/**
*
*/
private FileUploadField fileUpload;
private String UPLOAD_FOLDER = "..\\Promociones\\";
private static final long serialVersionUID = 1L;
#SuppressWarnings({ "rawtypes", "unchecked" })
public AddPromo(){
add(new Label("user",ActiveUser.USER));
//Add Feedback panel
add(new FeedbackPanel("feedback_2"));
//LOGOUT LINK
Logout logoutLink = new Logout("logout");
add(logoutLink);
//Add backlink to SuccesPage
add(new Link("link_atras"){
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public void onClick(){
SuccesPage nueva = new SuccesPage("",1);
setResponsePage(nueva);
}
});
//Definitions for date attributes
final Locale selectedLocale = Session.get().getLocale();
add(new StaticImage("image_test",new Model("http://1-ps.googleusercontent.com/h/www.bizreport.com/2011/02/03/200x200xandroid-logo-200x200.jpg.pagespeed.ic.SONOBLzFc5.jpg")));
Form<?> form = new Form<Void>("form") {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit() {
JPEGDim dims = new JPEGDim();
final FileUpload uploadedFile = fileUpload.getFileUpload();
if (uploadedFile != null) {
// write to a new file
File newFile = new File(UPLOAD_FOLDER
+ uploadedFile.getClientFileName());
try {
final Dimension d = dims.getJPEGDimension(newFile);
if (d.getWidth()==1024 || d.getHeight()==768 ) {
try {
if (newFile.exists()) {
newFile.delete();
}
newFile.createNewFile();
uploadedFile.writeTo(newFile);
info("saved file: " + uploadedFile.getClientFileName());
info("Imagen cumple con dimensiones " + d.getHeight() + " x " + d.getWidth());
} catch (Exception e) {
throw new IllegalStateException("Error "+e.toString());
}
} else {
error("Archivo no valido... " + + d.getHeight() + " x " + d.getWidth());
}
} catch (IOException e1) {
// TODO Auto-generated catch block
error(e1.toString());
}
}
}
};
// Enable multipart mode (need for uploads file)
form.setMultiPart(true);
// max upload size, 10k
form.setMaxSize(Bytes.megabytes(10));
form.add(fileUpload = new FileUploadField("fileUpload"));
add(form);
}
class JPEGDim {
public Dimension getJPEGDimension(File f) throws IOException {
FileInputStream fis = new FileInputStream(f);
// check for SOI marker
if (fis.read() != 255 || fis.read() != 216)
throw new RuntimeException("SOI (Start Of Image) marker 0xff 0xd8 missing");
Dimension d = null;
while (fis.read() == 255) {
int marker = fis.read();
int len = fis.read() << 8 | fis.read();
if (marker == 192) {
fis.skip(1);
int height = fis.read() << 8 | fis.read();
int width = fis.read() << 8 | fis.read();
d = new Dimension(width, height);
break;
}
fis.skip(len - 2);
}
fis.close();
return d;
}
}
}

Categories