问题
My server sends a encoded Base64 string to my android device. After that, I decode the Base64 string in this method to make a drawable of it. I can't see the image when I add it in an Itemizedoverlay.
public Drawable seticon(String input){
byte[] b = Base64.decode(input, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(b, 0, b.length);
Drawable drawable = new BitmapDrawable(decodedByte);
drawable.setBounds(0, 0, 50, 50);
return drawable;
}
public void setphotopoint(String input){
Drawable drawable = seticon(input);
PhotoOverlay aPhotoOverlay = new PhotoOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem();
overlayitem.setMarker(drawable);
aPhotoOverlay.addOverlay(overlayitem);
overlays.add(aPhotoOverlay);
}
this is my PhotoOverlay class
public class PhotoOverlay extends ItemizedOverlay<OverlayItem>{
private ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
Context mContext ;
public PhotoOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
this.mContext = context;
}
public PhotoOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
protected boolean onTap(int index) {
return true;
}
public void addOverlay(OverlayItem overlay) {
items.add(overlay);
//setLastFocusedIndex(-1);
populate();
}
@Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return items.get(i);
}
public void clear() {
items.clear();
populate();
}
public void removeOverlay(OverlayItem overlay) {
items.remove(overlay);
populate();
}
@Override
public int size() {
// TODO Auto-generated method stub
return items.size();
}
}
回答1:
Convert your binary file to Base64 then use the following code to retrieve it:
public static void base64ToFile(String path, String strBase64)
throws IOException {
byte[] bytes = Base64.decode(strBase64);
byteArrayTofile(path, bytes);
}
public static void byteArrayTofile(String path, byte[] bytes)
throws IOException {
File imagefile = new File(path);
File dir = new File(imagefile.getParent());
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(imagefile);
fos.write(bytes);
fos.close();
}
converting binary file to Base64:
public static String fileToBase64(String path) throws IOException {
byte[] bytes = fileToByteArray(path);
return Base64.encodeBytes(bytes);
}
public static byte[] fileToByteArray(String path) throws IOException {
File imagefile = new File(path);
byte[] data = new byte[(int) imagefile.length()];
FileInputStream fis = new FileInputStream(imagefile);
fis.read(data);
fis.close();
return data;
}
来源:https://stackoverflow.com/questions/10159972/how-do-i-decode-a-jpeg-image-encoded-in-base64-in-android-and-see-it-on-an-image