#ifdef _CUR_SYS_LINUX_
#include <iconv.h>
#else
#include <windows.h>
#include <stdio.h>
#endif
QByteArray ViewImage::AnsiToUtf8(QByteArray &ansi)
{
#ifdef _CUR_SYS_LINUX_
QByteArray utf8;
char *buf = new char[ansi.size() * 2];
char utf8Buf[] = { "utf-8" };
char gb2312Buf[] = { "gb2312" };
//ansi.resize(ansi.size()*2);
int code = code_convert(gb2312Buf, utf8Buf, ansi.data(), ansi.size(), buf, 2 * ansi.size());
if (code == -1) {
delete[]buf;
utf8 = "";
return utf8;
}
utf8 = buf;
delete[]buf;
return utf8;
#else
int len;
QByteArray result;
//ANSI转UNICODE
len = MultiByteToWideChar(CP_ACP, NULL, ansi.data(), -1, NULL, 0);
WCHAR * unicode = new WCHAR[len + 1];
memset(unicode, 0, len * 2 + 2);
MultiByteToWideChar(CP_ACP, NULL, ansi.data(), -1, unicode, len);
//UNICODE转utf8
len = WideCharToMultiByte(CP_UTF8, 0, unicode, -1, NULL, 0, NULL, NULL);
char *utf8 = new char[len + 1];
memset(utf8, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, unicode, -1, utf8, len, NULL, NULL);
//赋值
result = utf8;
delete[] unicode;
delete[] utf8;
return result;
#endif
}
使用方法:
QString utf8_str = QString(AnsiToUtf8(QByteArray(ansi_str.c_str())));